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
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
[WS_METHODS.peerLinksList]: AuthAccessReadScope,
[WS_METHODS.peerLinksEnvironments]: AuthAccessReadScope,
[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
[WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ export const make = Effect.gen(function* () {
threadInbox: true,
mcpModeLimitHeader: true,
linkFence: true,
linkedAppPairing: true,
mcpApprovalCodes: true,
mcpHostedApproval: true,
shellThreadFamilies: true,
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ export const clientModeCeiling = (client: McpClientCaller | undefined): ClientMo
};
};

/**
* The access a client app added through a link gets (`t3_link_app_pairing`). A
* client session has no runtime-mode ceiling, so it may act only when the link
* may act in any mode: full access, not narrowed. Anything else reads.
*/
export const linkedAppAccess = (client: McpClientCaller): "read-only" | "full-access" => {
const ceiling = clientModeCeiling(client);
return client.access === "full-access" &&
ceiling.runtimeMode === "full-access" &&
ceiling.interactionMode === "default"
? "full-access"
: "read-only";
};

/**
* A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
* itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
Expand Down Expand Up @@ -256,3 +270,10 @@ export const requireThreadScope = (scope: McpInvocationScope, operation: string)
scope.thread === undefined
? Effect.fail(threadCallerRequired(operation))
: Effect.succeed(scope as McpThreadInvocationScope);

/** `McpSchema.EnabledWhen` for tools only another environment's link may call. */
export const onlyForLinks = (): boolean => {
const fiber = Fiber.getCurrent();
const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
return scope?.client?.linked === true && scope.linkedEnvironments !== false;
};
63 changes: 60 additions & 3 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { OrchestratorMcpFailure } from "@t3tools/contracts";
import { mcpClientScopes, OrchestratorMcpFailure } from "@t3tools/contracts";
import { OrchestratorToolkit } from "./tools.ts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";

import * as EnvironmentAuth from "../../../auth/EnvironmentAuth.ts";

import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
Expand All @@ -12,6 +16,56 @@ import * as McpToolAccess from "../../McpToolAccess.ts";
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";

/**
* The link already holds this access here, so the client it adds holds no more. Auth is taken
* once, when the handlers are built, so harnesses that never pair need not provide it.
*/
export const linkAppPairing = Effect.map(
Effect.serviceOption(EnvironmentAuth.EnvironmentAuth),
(environmentAuth) =>
McpToolAccess.reads(() =>
Effect.gen(function* () {
const { client } = yield* McpInvocationContext.McpInvocationContext;
if (client?.linked !== true) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Only a linked T3 Code environment can add this one to its app.",
});
}
// A call the link makes for one of its agent threads: an agent never gets a credential.
if (client.senderThread !== undefined) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Only the linked environment's app can add this one, not its agents.",
});
}
if (Option.isNone(environmentAuth)) {
return yield* new OrchestratorMcpFailure({
code: "orchestration_error",
message: "This environment cannot issue pairing codes here.",
});
}
const access = McpInvocationContext.linkedAppAccess(client);
const issued = yield* environmentAuth.value
.issuePairingCredential({
scopes: mcpClientScopes(access),
label: `${client.label} (app)`,
})
.pipe(
Effect.mapError(
(error) =>
new OrchestratorMcpFailure({ code: "capability_denied", message: error.message }),
),
);
return {
credential: issued.credential,
expiresAt: DateTime.formatIso(issued.expiresAt),
access,
};
}),
),
);

const handlers = {
orchestrator_capabilities: McpToolAccess.reads((input) =>
Effect.gen(function* () {
Expand Down Expand Up @@ -237,6 +291,9 @@ const handlers = {
return yield* service.interruptThread(scope, input);
}),
),
} satisfies McpToolAccess.Handlers<typeof OrchestratorToolkit.tools>;
} satisfies Omit<McpToolAccess.Handlers<typeof OrchestratorToolkit.tools>, "t3_link_app_pairing">;

export const layer = McpToolAccess.toLayer(OrchestratorToolkit, handlers);
export const layer = McpToolAccess.toLayer(
OrchestratorToolkit,
Effect.map(linkAppPairing, (pairing) => ({ ...handlers, t3_link_app_pairing: pairing })),
);
15 changes: 15 additions & 0 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
OrchestratorMcpEnvironmentLinksResult,
OrchestratorMcpEnvironmentUnlinkInput,
OrchestratorMcpEnvironmentUnlinkResult,
OrchestratorMcpLinkAppPairingResult,
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskInput,
Expand Down Expand Up @@ -362,6 +363,19 @@ const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", {
.annotate(Tool.Idempotent, true)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileLinksOff);

// Offered to another environment's link only, never to an agent.
export const LinkAppPairingTool = Tool.make("t3_link_app_pairing", {
description:
"For a linked T3 Code environment: a one-time pairing code that adds this environment to its own app, at no more than the link's access.",
success: OrchestratorMcpLinkAppPairingResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies: [McpInvocationContext.McpInvocationContext],
})
.annotate(Tool.Title, "Add this environment to a linked app")
.annotate(Tool.Destructive, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.onlyForLinks);

export const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilitiesTool,
DelegateTaskTool,
Expand All @@ -383,4 +397,5 @@ export const OrchestratorToolkit = Toolkit.make(
EnvironmentLinksTool,
EnvironmentLinkTool,
EnvironmentUnlinkTool,
LinkAppPairingTool,
);
3 changes: 3 additions & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ const RPC_AGGREGATES = {
[WS_METHODS.peerLinksList]: "peerLinks",
[WS_METHODS.peerLinksLink]: "peerLinks",
[WS_METHODS.peerLinksUnlink]: "peerLinks",
[WS_METHODS.peerLinksAddToApp]: "peerLinks",
[WS_METHODS.peerLinksEnvironments]: "peerLinks",
[WS_METHODS.peerLinksReportAppConnections]: "peerLinks",
[WS_METHODS.peerLinksAnswerRequest]: "peerLinks",
[WS_METHODS.serverGetSettings]: "server",
[WS_METHODS.serverUpdateSettings]: "server",
Expand Down
186 changes: 186 additions & 0 deletions apps/server/src/peer/LinkAppPairing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { NodeHttpServer } from "@effect/platform-node";
import { expect, it } from "@effect/vitest";
import {
type AuthMcpClientAccess,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
EnvironmentId,
type OrchestratorMcpFailure,
OrchestratorMcpLinkAppPairingResult,
ProviderInstanceId,
type RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { Toolkit } from "effect/ai";

import * as McpHttpServer from "../mcp/McpHttpServer.ts";
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import * as McpToolAccess from "../mcp/McpToolAccess.ts";
import { linkAppPairing } from "../mcp/toolkits/orchestrator/handlers.ts";
import { LinkAppPairingTool } from "../mcp/toolkits/orchestrator/tools.ts";
import * as PeerLinks from "./PeerLinks.ts";
import * as PeerMcpClient from "./PeerMcpClient.ts";
import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";

const toolkit = Toolkit.make(LinkAppPairingTool);

it.effect.each<{
readonly access: AuthMcpClientAccess;
readonly narrowedTo: RuntimeMode;
readonly added: "read-only" | "full-access";
}>([
{ access: "read-only", narrowedTo: "full-access", added: "read-only" },
{ access: "auto", narrowedTo: "full-access", added: "read-only" },
{ access: "full-access", narrowedTo: "auto", added: "read-only" },
{ access: "full-access", narrowedTo: "full-access", added: "full-access" },
])(
"a $access link narrowed to $narrowedTo adds a $added app there",
({ access, narrowedTo, added }) =>
Effect.scoped(
Effect.gen(function* () {
const box = descriptorOf("environment-box", "Box", { linkedAppPairing: true });
const handlers = McpToolAccess.toLayer(
toolkit,
Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })),
);
const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
const context = yield* Layer.build(
layerLinkingEnvironment(descriptorOf("environment-a", "A")),
);
yield* linkTo(Context.get(context, PeerLinks.PeerLinks), b, access);
const issued = yield* Context.get(context, PeerMcpClient.PeerMcpClient).call({
environmentId: box.environmentId,
tool: "t3_link_app_pairing",
arguments: {},
limits: { runtimeMode: narrowedTo, interactionMode: "default" },
success: OrchestratorMcpLinkAppPairingResult,
});
expect(issued.access).toBe(added);
// The peer lists it with its pairing links, so it can be revoked there before use.
const listed = (yield* b.auth.listPairingLinks()).find(
(link) => link.label === "T3 Code · A (app)",
);
expect(listed?.permissions).toContain(AuthOrchestrationReadScope);
expect(listed?.permissions?.includes(AuthOrchestrationOperateScope)).toBe(
added === "full-access",
);
// Asking for more when it is spent gets no more than it carries.
if (added === "read-only") {
const broader = yield* b.auth
.exchangeBootstrapCredentialForAccessToken(
issued.credential,
[AuthOrchestrationOperateScope],
{ deviceType: "desktop" },
)
.pipe(Effect.flip);
expect(broader._tag).toBe("ServerAuthScopeNotGrantedError");
}
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

const caller = (
client: Partial<McpInvocationContext.McpClientCaller> | undefined,
thread?: McpInvocationContext.McpThreadCaller,
): McpInvocationContext.McpInvocationScope => ({
environmentId: EnvironmentId.make("environment-box"),
requestNamespace: "caller",
thread,
client:
client === undefined
? undefined
: { sessionId: "session", label: "Caller", access: "full-access", ...client },
capabilities: new Set(["orchestration"]),
issuedAt: 0,
linkedEnvironments: true,
});

// Discovery offers the tool to links only. The handler must refuse everyone else on its own.
it.effect.each<{
readonly name: string;
readonly scope: McpInvocationContext.McpInvocationScope;
readonly code: OrchestratorMcpFailure["code"];
}>([
{ name: "an outside agent", scope: caller({}), code: "capability_denied" },
{
name: "an agent's thread here",
scope: caller(undefined, {
threadId: ThreadId.make("thread:agent"),
providerSessionId: "provider:agent",
providerInstanceId: ProviderInstanceId.make("codex"),
}),
code: "capability_denied",
},
{
name: "a link calling for one of its agent threads",
scope: caller({
linked: true,
senderThread: {
environmentId: EnvironmentId.make("environment-a"),
threadId: ThreadId.make("thread:linked-agent"),
title: "Agent",
},
}),
code: "capability_denied",
},
// The link itself gets past both checks, to where this harness has no pairing.
{ name: "the link itself", scope: caller({ linked: true }), code: "orchestration_error" },
])("$name calling t3_link_app_pairing gets $code", ({ scope, code }) =>
Effect.gen(function* () {
const built = yield* toolkit;
const { result } = yield* built
.handle("t3_link_app_pairing", {})
.pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption));
expect(result).toMatchObject({ code });
}).pipe(
Effect.provide(
McpToolAccess.HandlersLayer.layer(
McpToolAccess.toLayer(
toolkit,
Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })),
),
),
),
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
),
);

it.effect("refuses a link's call made for one of its agent threads", () =>
Effect.scoped(
Effect.gen(function* () {
const box = descriptorOf("environment-box", "Box", { linkedAppPairing: true });
const handlers = McpToolAccess.toLayer(
toolkit,
Effect.map(linkAppPairing, (pairing) => ({ t3_link_app_pairing: pairing })),
);
const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
const context = yield* Layer.build(
layerLinkingEnvironment(descriptorOf("environment-a", "A")),
);
yield* linkTo(Context.get(context, PeerLinks.PeerLinks), b, "full-access");
const refused = yield* Context.get(context, PeerMcpClient.PeerMcpClient)
.call({
environmentId: box.environmentId,
tool: "t3_link_app_pairing",
arguments: {},
limits: { runtimeMode: "full-access", interactionMode: "default" },
sender: {
environmentId: EnvironmentId.make("environment-a"),
threadId: ThreadId.make("thread:linked-agent"),
title: "Agent",
},
success: OrchestratorMcpLinkAppPairingResult,
})
.pipe(Effect.flip);
expect(refused.code).toBe("capability_denied");
expect(
(yield* b.auth.listPairingLinks()).some((link) => link.label === "T3 Code · A (app)"),
).toBe(false);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
Loading
Loading