Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,21 @@ const withSenderThread = (
: { ...invocation, client: { ...invocation.client, senderThread: decoded.value } };
};

/** Records what a linked environment's tools support; anything malformed reads as none. */
const withPeerFeatures = (
invocation: McpInvocationContext.McpInvocationScope,
request: HttpServerRequest.HttpServerRequest,
): McpInvocationContext.McpInvocationScope => {
const header = request.headers[McpInvocationContext.PEER_FEATURES_HEADER];
if (header === undefined || invocation.client?.linked !== true) return invocation;
const peerFeatures = header
.split(",")
.map((feature) => feature.trim())
.filter((feature) => /^[a-z0-9-]{1,64}$/.test(feature))
.slice(0, 32);
return { ...invocation, client: { ...invocation.client, peerFeatures } };
};

// The Linked environments beta is off here: links wait until it is on again.
const linkedEnvironmentsOff = HttpServerResponse.jsonUnsafe(
{
Expand Down Expand Up @@ -270,7 +285,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
});
}
const asked = withModeLimit(withSenderThread(invocation, request), request);
const asked = withModeLimit(
withPeerFeatures(withSenderThread(invocation, request), request),
request,
);
if (asked === undefined) return invalidModeLimit;
const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
const linkedEnvironments = yield* linksEnabled;
Expand Down
18 changes: 18 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
type EnvironmentId,
McpCapabilityUnavailableError,
OrchestratorMcpFailure,
PEER_FEATURE_INBOX_REASON,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ProviderInteractionMode,
Expand Down Expand Up @@ -48,6 +49,8 @@ export interface McpClientCaller {
readonly narrowedTo?: ClientModes | undefined;
/** A linked environment's thread this request is made for (`T3-Sender-Thread`). */
readonly senderThread?: OrchestrationV2LinkedSender | undefined;
/** What a linked environment says its tools support (`T3-Peer-Features`); none from older ones. */
readonly peerFeatures?: ReadonlyArray<string> | undefined;
/** An outside client's thread links go through this hosted app, as Copy thread's do. */
readonly hostedAppUrl?: string | undefined;
}
Expand All @@ -67,6 +70,21 @@ export const MODE_LIMIT_HEADER = "t3-mode-limit";
*/
export const SENDER_THREAD_HEADER = "t3-sender-thread";

/**
* `T3-Peer-Features: <feature>,<feature>`: what a linked environment's tools support, so this
* side can tell an older release from a current one (its `clientInfo` version never changes).
* Read only from a linked client. A missing header means a release from before it.
*/
export const PEER_FEATURES_HEADER = "t3-peer-features";

/** Features this release's peer client announces on every call. */
export const PEER_FEATURES: ReadonlyArray<string> = [PEER_FEATURE_INBOX_REASON];

/** A linked environment whose tools cannot send `inboxRouting.reason`. */
export const isLegacyInboxPeer = (scope: Pick<McpInvocationScope, "client">): boolean =>
scope.client?.linked === true &&
!(scope.client.peerFeatures ?? []).includes(PEER_FEATURE_INBOX_REASON);

export interface ClientModes {
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
Expand Down
13 changes: 10 additions & 3 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import {
SECRET_REQUEST_UNSAVED_NOTE,
agentLaunchInboxError,
agentLaunchInboxRouting,
withLegacyPeerInboxReason,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
Expand Down Expand Up @@ -127,6 +128,7 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts
import * as ServerSettings from "../serverSettings.ts";
import {
clientModeCeiling,
isLegacyInboxPeer,
type McpInvocationScope,
type McpThreadInvocationScope,
requireThreadScope,
Expand Down Expand Up @@ -3126,12 +3128,17 @@ const make = Effect.gen(function* () {
createThreads: Effect.fn("OrchestratorMcpService.createThreads")(
function* (callerScope, input) {
const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads");
for (const request of input.threads) {
// An older linked environment cannot send a reason; file its threads as FYI, not a dead end.
const legacyPeer = isLegacyInboxPeer(callerScope);
const threads = input.threads.map((request) =>
withLegacyPeerInboxReason(request, legacyPeer),
);
for (const request of threads) {
const inboxError = agentLaunchInboxError(request);
if (inboxError !== null) return yield* failure("invalid_request", inboxError);
}
// Each thread shares this thread's checkout, so another environment cannot take it.
for (const request of input.threads) {
for (const request of threads) {
yield* admitPlacement(
chooseThreadPlacement(
{
Expand Down Expand Up @@ -3160,7 +3167,7 @@ const make = Effect.gen(function* () {
const providers = yield* loadProviders;
const key = yield* requestKey(input.clientRequestId);
const created = yield* Effect.forEach(
input.threads,
threads,
(request, index) =>
Effect.gen(function* () {
const commandId = stableCommandId({
Expand Down
7 changes: 5 additions & 2 deletions apps/server/src/mcp/ThreadMetadataMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type ThreadMetadataMcpUpdateResult,
ThreadId,
routeThreadInbox,
withLegacyPeerInboxReason,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
Expand All @@ -18,7 +19,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
import { isLegacyInboxPeer, type McpInvocationScope } from "./McpInvocationContext.ts";
import { threadNotFound } from "./threadAccess.ts";

export class ThreadMetadataMcpService extends Context.Service<
Expand Down Expand Up @@ -151,8 +152,10 @@ const make = Effect.gen(function* () {

const update = Effect.fn("ThreadMetadataMcpService.update")(function* (
scope: McpInvocationScope,
input: ThreadMetadataMcpUpdateInput,
requested: ThreadMetadataMcpUpdateInput,
) {
// An older linked environment cannot send a reason; file its route as FYI, not a dead end.
const input = withLegacyPeerInboxReason(requested, isLegacyInboxPeer(scope));
if (!scope.capabilities.has("orchestration")) {
return yield* failure(
"capability_denied",
Expand Down
12 changes: 9 additions & 3 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
agentLaunchInboxError,
agentLaunchInboxRouting,
withLegacyPeerInboxReason,
CommandId,
type EnvironmentId,
MessageId,
Expand Down Expand Up @@ -261,6 +262,11 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
const scope = yield* McpInvocationContext.McpInvocationContext;
const context = yield* readCaller();
const { caller } = context;
// An older linked environment cannot send a reason; file its launch as FYI, not a dead end.
const filed = withLegacyPeerInboxReason(
input,
McpInvocationContext.isLegacyInboxPeer(scope),
);
// A retry with the same key replays the first launch: the ids derive
// from the caller and the key, and the launch service replays a
// command it already accepted.
Expand All @@ -271,7 +277,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
const threadId = ThreadId.make(commandId);
const messageId = MessageId.make(commandId);
const attachments = input.attachments ?? [];
const inboxError = agentLaunchInboxError(input);
const inboxError = agentLaunchInboxError(filed);
if (inboxError !== null)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
Expand Down Expand Up @@ -366,7 +372,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
// A launch already made here replays here. Any other is placed, or reaches the
// environment its key was placed in, before anything only this checkout checks.
if (!replaying) {
const placedThere = yield* launchPlacedThere(scope, input, {
const placedThere = yield* launchPlacedThere(scope, filed, {
projectId,
threadId,
strategy,
Expand Down Expand Up @@ -434,7 +440,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
}
const result = yield* ThreadMessageIntake.launchThread({
inboxOrigin: { kind: "agent", id: caller?.id ?? "agent" },
inboxRouting: agentLaunchInboxRouting(input),
inboxRouting: agentLaunchInboxRouting(filed),
commandId,
threadId,
projectId,
Expand Down
52 changes: 52 additions & 0 deletions apps/server/src/peer/PeerMcpClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,58 @@ it.effect("tells the peer which thread a call is made for", () =>
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

const featuresToolkit = Toolkit.make(
Tool.make("features", {
description: "Returns what the calling peer says it supports.",
success: Schema.Struct({ legacy: Schema.Boolean, features: Schema.Array(Schema.String) }),
dependencies: [McpInvocationContext.McpInvocationContext],
}),
);

it.effect("announces this release's peer features, so the peer can tell it from an older one", () =>
Effect.scoped(
Effect.gen(function* () {
const handlers = McpToolAccess.toLayer(featuresToolkit, {
features: McpToolAccess.reads(() =>
McpInvocationContext.McpInvocationContext.pipe(
Effect.map((scope) => ({
legacy: McpInvocationContext.isLegacyInboxPeer(scope),
features: [...(scope.client?.peerFeatures ?? [])],
})),
),
),
});
const box = descriptorOf("environment-box", "Box");
const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(featuresToolkit, handlers));
const context = yield* Layer.build(
layerLinkingEnvironment(descriptorOf("environment-a", "A")),
);
const links = Context.get(context, PeerLinks.PeerLinks);
const client = Context.get(context, PeerMcpClient.PeerMcpClient);
yield* linkTo(links, b);
const seen = yield* client.call({
environmentId: box.environmentId,
tool: "features",
arguments: {},
limits: { runtimeMode: "full-access", interactionMode: "default" },
success: Schema.Struct({ legacy: Schema.Boolean, features: Schema.Array(Schema.String) }),
});
// A current peer must still give inboxRouting.reason; only one without the header is legacy.
expect(seen).toEqual({ legacy: false, features: ["inbox-reason"] });
expect(
McpInvocationContext.isLegacyInboxPeer({
client: { sessionId: "s", label: "old desktop", access: "full-access", linked: true },
}),
).toBe(true);
expect(
McpInvocationContext.isLegacyInboxPeer({
client: { sessionId: "s", label: "browser", access: "full-access" },
}),
).toBe(false);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect.each([false, true])(
"reuses an initialized session before its first call finishes (cancelled: %s)",
(cancelFirst) =>
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/peer/PeerMcpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ const make = Effect.gen(function* () {
{
...limitHeader,
...senderHeader,
[McpInvocationContext.PEER_FEATURES_HEADER]:
McpInvocationContext.PEER_FEATURES.join(","),
"mcp-session-id": sessionId,
"mcp-protocol-version": PROTOCOL_VERSION,
},
Expand Down
48 changes: 48 additions & 0 deletions packages/contracts/src/threadInbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
projectThreadInbox,
inboxRoutingFor,
primaryInbox,
withLegacyPeerInboxReason,
type ThreadInboxRoutingPatch,
} from "./threadInbox.ts";
const kameron = { kind: "human", id: "kameron" } as const;
Expand Down Expand Up @@ -146,6 +147,53 @@ describe("shared fleet organizational inbox", () => {
expect(visibleIn(quieter)).toEqual(["kameron", "agents"]);
expect(founderInboxLane(quieter, "kameron")).toBe("FYI");
});

it("files an older linked environment's reason-less founder routes as FYI instead of failing", () => {
// A peer from before `inboxRouting.reason` has no such field in its tools: rejecting the
// route for a missing reason left its agent no way to succeed.
const toKameron = { assignee: kameron } as const;
const routed = (routing: ThreadInboxRoutingPatch) =>
routeThreadInbox(makeThreadInbox({ actor: bot }), routing);
expect(agentInboxRoutingError(routed(toKameron), toKameron)).toContain("inboxRouting.reason");

const legacy = withLegacyPeerInboxReason({ inboxRouting: toKameron }, true);
expect(legacy.inboxRouting).toEqual({ assignee: kameron, reason: "fyi" });
expect(agentInboxRoutingError(routed(legacy.inboxRouting), legacy.inboxRouting)).toBeNull();
expect(founderInboxLane(routed(legacy.inboxRouting), "kameron")).toBe("FYI");

const launch = withLegacyPeerInboxReason({ inbox: "kameron" as const }, true);
expect(agentLaunchInboxError(launch)).toBeNull();
expect(
founderInboxLane(
makeThreadInbox({ actor: bot, routing: agentLaunchInboxRouting(launch) }),
"kameron",
),
).toBe("FYI");

// A current peer announces the feature and still must give a reason.
expect(withLegacyPeerInboxReason({ inboxRouting: toKameron }, false).inboxRouting).toEqual(
toKameron,
);
expect(
agentLaunchInboxError(withLegacyPeerInboxReason({ inbox: "kameron" as const }, false)),
).toContain("inboxRouting.reason");
// A reason the older peer did send, and a launch that names no inbox, are left alone.
const reviewed = { inboxRouting: { assignee: kameron, reason: "review" as const } };
expect(withLegacyPeerInboxReason(reviewed, true)).toBe(reviewed);
const plain = { title: "x", inboxRouting: undefined };
expect(withLegacyPeerInboxReason(plain, true)).toBe(plain);
// A route that stays in Agents gets no reason stamped on it.
for (const agentsOnly of [
{ inboxRouting: {} },
{ inboxRouting: { assignee: null } },
{ inbox: "agents" as const },
])
expect(withLegacyPeerInboxReason(agentsOnly, true)).toBe(agentsOnly);
// The shared inbox is a founder inbox too: filed as FYI, not rejected.
expect(
agentLaunchInboxError(withLegacyPeerInboxReason({ inbox: "shared" as const }, true)),
).toBeNull();
});
it("shows reason-less agent lanes only to the founder they were routed to, as FYI", () => {
const people = [null, kameron, jeff] as const;
const patches: ThreadInboxRoutingPatch[] = [{}];
Expand Down
26 changes: 26 additions & 0 deletions packages/contracts/src/threadInbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,32 @@ export function agentInboxRoutingError(
return "Agent work files into the Agents inbox and reports one final result there. Put a thread in a founder's or the shared inbox only when they will converse in it, review, decide or approve: pass inboxRouting.reason ('conversation', 'review', 'decision', 'approval' or 'fyi'). To ask a founder something on a thread, use t3_thread_update action:'request_decision' and also write the question in the thread, where they read it. If the answer reaches you another way, such as a relayed approval, call action:'resolve_decision'.";
}

/**
* What a linked environment sends in `T3-Peer-Features` once its tools forward
* `inboxRouting.reason`. Releases before it have no such field in their tool schema, so their
* agents cannot give a reason at all.
*/
export const PEER_FEATURE_INBOX_REASON = "inbox-reason" as const;

/**
* Files a reason-less route from an older linked environment as `fyi` instead of rejecting it:
* that agent's tools cannot send a reason, so the rejection would be a dead end. `fyi` is what
* lanes filed before reasons existed already show as (see `founderInboxLane`). Routes that
* carry a reason, and routes that touch no inbox, are returned unchanged.
*/
export function withLegacyPeerInboxReason<
T extends {
readonly inbox?: InboxChoice | undefined;
readonly inboxRouting?: ThreadInboxRoutingPatch | undefined;
},
>(input: T, legacyPeer: boolean): T {
if (!legacyPeer || input.inboxRouting?.reason !== undefined) return input;
// Only a route the strict guard would reject: one that reaches a founder or the shared inbox.
// A route that stays in Agents keeps no reason.
if (agentLaunchInboxError(input) === null) return input;
return { ...input, inboxRouting: { ...input.inboxRouting, reason: "fyi" } };
}

/** The rejection for an agent launch filed by `agentLaunchInboxRouting`, or null. */
export const agentLaunchInboxError = (input: Parameters<typeof agentLaunchInboxRouting>[0]) => {
const routing = agentLaunchInboxRouting(input);
Expand Down
Loading