From 673d27720142eacfb26837b3531b9853395e1cff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 19:31:06 +0000 Subject: [PATCH 1/4] test(server): MCP OAuth caps the grant at the requested scope Fails on main: a client that requests only orchestration:read and is approved at Auto gets an orchestration:operate token (#38296). Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/McpOAuth.test.ts | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..3e811783710c0 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -400,6 +400,43 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", () ), ); +it.live("caps the grant at the scope the client requested", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const pairing = yield* auth.issuePairingCredential(); + const params = { ...authorizeParams(clientId), scope: "orchestration:read" }; + + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "auto", + code: pairing.credential, + }); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const token = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + resource: `${ORIGIN}/mcp`, + }), + ), + ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>)); + expect(token.scope).toBe("orchestration:read"); + const client = yield* auth.authenticateMcpClient( + HttpServerRequest.fromWeb( + at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), + ), + ); + expect(client).toMatchObject({ access: "read-only" }); + }), + ), +); + it.live("signs in a hosted agent with an https callback that asked for a client secret", () => withRoutes((handler, auth) => Effect.gen(function* () { From 561aa55e1be447111aef38f296e44f38276600aa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 19:02:34 +0000 Subject: [PATCH 2/4] fix(server): MCP OAuth caps the grant at the scope the client requested A client that asked only for orchestration:read got whatever level the approver picked, so Auto or Full access gave it operate (and write) tools. The authorize request now carries scope; a read-only request caps any approval at read only, and the consent page shows that level. Fixes pingdotgg/t3code#38296 Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/McpOAuth.test.ts | 4 ++++ apps/server/src/auth/McpOAuth.ts | 11 ++++++++++- apps/server/src/auth/mcpOAuthHttp.ts | 1 + apps/web/src/components/auth/ConnectAgentSurface.tsx | 10 ++++++---- packages/contracts/src/auth.ts | 3 +++ 5 files changed, 24 insertions(+), 5 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index 3e811783710c0..9179ce22214ea 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -406,6 +406,10 @@ it.live("caps the grant at the scope the client requested", () => const clientId = yield* registeredClientId(handler); const pairing = yield* auth.issuePairingCredential(); const params = { ...authorizeParams(clientId), scope: "orchestration:read" }; + const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe( + Effect.flatMap(json<{ requestedAccess?: string }>), + ); + expect(details.requestedAccess).toBe("read-only"); const approved = yield* decide(handler, params, { _tag: "pairing-code", diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 18ad10c2dbd28..edd47299023cb 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -19,7 +19,7 @@ import { type RuntimeMode, } from "@t3tools/contracts"; import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; -import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; +import { encodeOAuthScope, parseOAuthScope } from "@t3tools/shared/oauthScope"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; @@ -186,6 +186,8 @@ export interface AuthorizationRequest { readonly state: Redacted.Redacted | undefined; readonly resource: string; readonly issuer: string; + /** The client requested `orchestration:read` without `orchestration:operate`. */ + readonly readOnly: boolean; } interface PendingCode { @@ -413,6 +415,7 @@ const make = Effect.gen(function* () { if (!sameResource(urls, request.resource)) { return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`); } + const requestedScopes = request.scope === undefined ? null : parseOAuthScope(request.scope); return { client, redirectUri, @@ -420,6 +423,10 @@ const make = Effect.gen(function* () { state, resource: urls.resource, issuer: urls.issuer, + readOnly: + requestedScopes !== null && + requestedScopes.includes(AuthOrchestrationReadScope) && + !requestedScopes.includes(AuthOrchestrationOperateScope), } satisfies AuthorizationRequest; }); @@ -501,6 +508,8 @@ const make = Effect.gen(function* () { }); } } + // The approver chooses within what the client asked for. + if (input.authorization.readOnly) access = "read-only"; const code = yield* mintCode(input.authorization, access); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 6e10362000adf..143a0079b707e 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -176,6 +176,7 @@ export const layer = HttpApiBuilder.group( ...(oauth.runtimeModeCeiling === undefined ? {} : { runtimeModeCeiling: oauth.runtimeModeCeiling }), + ...(resolved.readOnly ? { requestedAccess: "read-only" as const } : {}), ...(session === undefined ? {} : { diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index 9d03091433610..c2283c9ca77ff 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -149,14 +149,16 @@ export function McpConsent({ const [requestedAccess, setAccess] = useState(null); const [pairingCode, setPairingCode] = useState(""); const [armed, setArmed] = useState(false); + const clientAccess = loaded.status === "ready" ? loaded.details.requestedAccess : undefined; const access = - requireLevelChoice && requestedAccess === null + clientAccess ?? + (requireLevelChoice && requestedAccess === null ? null : resolveMcpAccess( requestedAccess, loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined, pairingCode.trim().length > 0, - ); + )); const [errorMessage, setErrorMessage] = useState(""); const [pending, setPending] = useState<"approve" | "deny" | null>(null); @@ -250,8 +252,8 @@ export function McpConsent({ pending === null && access !== null && resolveApprovalDecision({ code: pairingCode, access, details }) !== null; - // A code from "Use T3 Code in another app" names its level, so the page does not ask again. - const codeAccess = parseMcpApprovalCode(pairingCode)?.access; + // A read-only request, or a code from "Use T3 Code in another app", fixes the level. + const codeAccess = details.requestedAccess ?? parseMcpApprovalCode(pairingCode)?.access; const approveLevel = codeAccess ?? access; return ( diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 132cc7322337b..d2eb357870465 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -600,6 +600,7 @@ export const AuthMcpAuthorizationRequest = Schema.Struct({ code_challenge_method: Schema.optionalKey(Schema.String), state: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)), resource: Schema.optionalKey(Schema.String), + scope: Schema.optionalKey(Schema.String), }); export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type; @@ -612,6 +613,8 @@ export const AuthMcpApprovalDetails = Schema.Struct({ csrfToken: Schema.optionalKey(Schema.String), /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */ oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)), + /** The client asked only to read, so any approval grants read only. */ + requestedAccess: Schema.optionalKey(Schema.Literal("read-only")), /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */ runtimeModeCeiling: Schema.optionalKey( Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }), From b8241b9a1585a2db4392dbf2b8f9181fc234156e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 19:56:19 +0000 Subject: [PATCH 3/4] fix(server): read-only MCP clients no longer list write tools A read-only MCP client was refused write tools when it called them, but tools/list still offered them (t3_thread_launch, t3_thread_send, t3_project_create and the rest). Each tool declaration now records whether it is a read, and a per-toolkit visibility leaves the others out of a read-only client's tool list. Calls still reach the handler, which answers capability_denied. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 113 ++++++++++++++++++++++ apps/server/src/mcp/McpHttpServer.ts | 14 +++ apps/server/src/mcp/McpToolAccess.ts | 53 +++++++--- docs/internals/environment-auth.md | 4 +- 4 files changed, 172 insertions(+), 12 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 5801a210ba6cf..e01f5f3266c73 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1695,6 +1695,119 @@ it.effect("hides tools for links and refuses another environment while the beta ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("lists only read tools to a read-only client and still refuses its writes", () => + Effect.scoped( + Effect.gen(function* () { + const AccessToolkit = Toolkit.make( + Tool.make("peek", { + description: "Reads.", + success: Schema.Struct({ ok: Schema.Boolean }), + failure: OrchestratorMcpFailure, + failureMode: "return", + }), + Tool.make("poke", { + description: "Writes.", + success: Schema.Struct({ ok: Schema.Boolean }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ], + }), + ); + const scopeFor = ( + token: string, + access: "read-only" | "auto", + ): McpInvocationContext.McpInvocationScope => ({ + environmentId, + requestNamespace: `client:${token}`, + thread: undefined, + client: { sessionId: token, label: "probe", access }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }); + const serverLayer = McpHttpServer.layerMcpTransport( + McpHttpServer.toolkitRegistration( + AccessToolkit, + McpToolAccess.toLayer(AccessToolkit, { + peek: McpToolAccess.reads(() => Effect.succeed({ ok: true })), + poke: McpToolAccess.writes(() => Effect.succeed({ ok: true })), + }), + ), + ).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: () => Effect.undefined, + }), + ), + Layer.provide( + Layer.succeed(McpHttpServer.McpClientAuthenticator, { + authenticate: (request) => { + const token = request.headers.authorization?.slice("Bearer ".length); + return Effect.succeed( + token === "reader" + ? scopeFor(token, "read-only") + : token === "operator" + ? scopeFor(token, "auto") + : undefined, + ); + }, + }), + ), + ); + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe( + Layer.build, + ); + const httpClient = yield* HttpClient.HttpClient; + const session = Effect.fn(function* (token: string) { + const headers = { + accept: "application/json, text/event-stream", + authorization: `Bearer ${token}`, + }; + const initialize = yield* httpClient.post("/mcp", { + headers, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`, + "application/json", + ), + }); + return (method: string, params: object) => + httpClient + .post("/mcp", { + headers: { + ...headers, + "mcp-session-id": initialize.headers["mcp-session-id"]!, + "mcp-protocol-version": "2025-06-18", + }, + body: HttpBody.text( + JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }), + "application/json", + ), + }) + .pipe( + Effect.flatMap((response) => response.json), + Effect.map((body) => (body as { result: Record }).result), + ); + }); + const names = (result: Record) => + (result.tools as ReadonlyArray<{ name: string }>).map((tool) => tool.name); + + const reader = yield* session("reader"); + expect(names(yield* reader("tools/list", {}))).toEqual(["peek"]); + expect(yield* reader("tools/call", { name: "poke", arguments: {} })).toMatchObject({ + isError: true, + content: [{ text: expect.stringContaining("approved for read-only access") }], + }); + + const operator = yield* session("operator"); + expect(names(yield* operator("tools/list", {}))).toEqual(["peek", "poke"]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("lists pull request watch tools only to threads that are not delegated children", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 9a85e5e01f3c5..611f62ff4ea5d 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1202,6 +1202,19 @@ const provideRegistrationServices = () => ), ); +/** Calls are still answered by the handler, which refuses them; only discovery changes. */ +const hiddenFromReadOnlyClients = McpServer.visibility( + Effect.gen(function* () { + const hidden = yield* McpToolAccess.ReadOnlyHiddenTools; + // Untraced: it runs once per tool on every list request. + return Effect.fnUntraced(function* ({ method, target }: McpServer.MiddlewareOptions) { + if (method !== "tools/list" || !hidden.has(target)) return true; + const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); + return Option.getOrUndefined(scope)?.client?.access !== "read-only"; + }); + }), +); + /** * Tools declare their handler services as request-level dependencies. Those * built with the server are provided here; `McpInvocationContext` is left to @@ -1224,6 +1237,7 @@ export const toolkitRegistration = , EX, >().layer, ), Layer.provide(McpServer.McpServer.layer), + Layer.provide(hiddenFromReadOnlyClients.layer), Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 20a9274798d0f..72206ff5ed361 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -13,7 +13,7 @@ import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Ref from "effect/Ref"; import * as Struct from "effect/Struct"; -import type * as Layer from "effect/Layer"; +import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; import { McpSchema } from "effect/ai"; import type { Tool, Toolkit } from "effect/ai"; @@ -49,6 +49,7 @@ let declare: ( handle: (params: P) => Effect.Effect, remote: RemoteCheck

| undefined, forwarded?: Forwarded, + reads?: boolean, ) => Declaration<(params: P) => Effect.Effect>; /** @@ -67,6 +68,7 @@ type Forwarded = ( environmentId: EnvironmentId, result: A, ) => Effect.Effect; +let readsOf: (declaration: Declaration) => boolean; let forwardedOf: ( declaration: Declaration, ) => Forwarded | undefined; @@ -80,33 +82,45 @@ interface CheckedHandler extends Struct.Lambda { let checkedHandler: CheckedHandler; let handlersLayer: , EX, RX>( - layer: Layer.Layer, EX, RX>, + layer: Layer.Layer | ReadOnlyHiddenTools, EX, RX>, ) => HandlersLayer; +/** The tools a read-only client may not call, left out of its tool list. */ +export class ReadOnlyHiddenTools extends Context.Service< + ReadOnlyHiddenTools, + ReadonlySet +>()("t3/mcp/McpToolAccess/ReadOnlyHiddenTools") {} + /** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */ export class Declaration { readonly #handle: Handler; readonly #remote: RemoteCheck | undefined; readonly #forwarded: Forwarded | undefined; + /** Whether a read-only client may call it; the others are hidden from its tool list. */ + readonly #reads: boolean; private constructor( token: typeof builtHere, handle: Handler, remote: RemoteCheck | undefined, forwarded: Forwarded | undefined, + reads: boolean, ) { refuseOutsideConstruction(token); this.#handle = handle; this.#remote = remote; this.#forwarded = forwarded; + this.#reads = reads; } static { - declare = (handle, remote, forwarded) => + declare = (handle, remote, forwarded, reads = false) => new Declaration( builtHere, handle, remote, forwarded as Forwarded | undefined, + reads, ); + readsOf = (declaration) => declaration.#reads; checkedHandler = Struct.lambda((declaration) => declaration.#handle); remoteCheckOf = (declaration) => declaration.#remote; forwardedOf = (declaration) => declaration.#forwarded; @@ -145,10 +159,17 @@ export const reads = (handle: (params: P) => Effect.Effect) declare( (params: P) => handle(params), () => Effect.void, + undefined, + true, ); export const readsAsCaller = (handle: (params: P) => Effect.Effect) => - declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined); + declare( + (params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), + undefined, + undefined, + true, + ); export const actsAsCaller = (handle: (params: P) => Effect.Effect) => declare( @@ -301,6 +322,8 @@ export const either = ( message: "This action acts as the calling thread, which is here. Omit environmentId.", }), ), + undefined, + readsOf(first) || readsOf(second), ); }; @@ -316,6 +339,7 @@ export const afterForwarding = ( checkedHandler(declaration) as (params: P) => Effect.Effect, remoteCheckOf(declaration) as RemoteCheck

| undefined, forwarded, + readsOf(declaration), ); const fullAccessRequired = @@ -366,10 +390,10 @@ export type Handlers> = Declarations< >; export class HandlersLayer, EX = never, RX = never> { - readonly #layer: Layer.Layer, EX, RX>; + readonly #layer: Layer.Layer | ReadOnlyHiddenTools, EX, RX>; private constructor( token: typeof builtHere, - layer: Layer.Layer, EX, RX>, + layer: Layer.Layer | ReadOnlyHiddenTools, EX, RX>, ) { refuseOutsideConstruction(token); this.#layer = layer; @@ -466,11 +490,18 @@ export const toLayer = , EX = never, RX = build: Handlers | Effect.Effect, EX, RX>, ): HandlersLayer> => { // Checked as soon as they are given, so a forged declaration fails here. - const withDeclarations = (declarations: Handlers) => - routed(toolkit, declarations, checkedHandlers(declarations)); + const layerFor = (declarations: Handlers) => + Layer.merge( + toolkit.toLayer(routed(toolkit, declarations, checkedHandlers(declarations))), + Layer.succeed(ReadOnlyHiddenTools)( + new Set( + Object.entries>(declarations) + .filter(([, declaration]) => !readsOf(declaration)) + .map(([name]) => name), + ), + ), + ); return handlersLayer( - toolkit.toLayer( - Effect.isEffect(build) ? Effect.flatMap(build, withDeclarations) : withDeclarations(build), - ), + Effect.isEffect(build) ? Layer.unwrap(Effect.map(build, layerFor)) : layerFor(build), ); }; diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index 973b0cc5dafaf..df35fd9808d07 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -55,8 +55,10 @@ state. Approval spends a one-time pairing code, or uses a browser session with The user grants either read-only access or a runtime-mode ceiling, not a scope list: MCP tools are all orchestration, and `orchestration:operate` alone would let an agent start a thread in full access and act through it. +A client whose `scope` asks for `orchestration:read` without +`orchestration:operate` gets read-only access whatever the user picks. The result is an ordinary session with subject `mcp-client`. A read-only -grant holds `orchestration:read` alone. On `/mcp` it passes only tools +grant holds `orchestration:read` alone. On `/mcp` it lists and passes only tools declared as reads in [McpToolAccess](../../apps/server/src/mcp/McpToolAccess.ts), where every tool must declare who may call it to compile. Any other grant adds `orchestration:operate` and a signed ceiling. Only `/mcp` accepts these sessions. Every other HTTP and WebSocket From 54446534edc730e6ef7ee4f744dfa378f6f2f146 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 20:16:26 +0000 Subject: [PATCH 4/4] fix(server): hide each toolkit's own write tools from read-only clients The read-only visibility was one module-level layer, so it was built once and kept the first toolkit's tool names; a second toolkit's write tools stayed listed. Each registration now builds its own. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 42 +++++++++++++++-------- apps/server/src/mcp/McpHttpServer.ts | 30 +++++++++------- 2 files changed, 44 insertions(+), 28 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 08b099da23d64..148ac2c103140 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1761,14 +1761,8 @@ it.effect("hides tools for links and refuses another environment while the beta it.effect("lists only read tools to a read-only client and still refuses its writes", () => Effect.scoped( Effect.gen(function* () { - const AccessToolkit = Toolkit.make( - Tool.make("peek", { - description: "Reads.", - success: Schema.Struct({ ok: Schema.Boolean }), - failure: OrchestratorMcpFailure, - failureMode: "return", - }), - Tool.make("poke", { + const writeTool = (name: Name) => + Tool.make(name, { description: "Writes.", success: Schema.Struct({ ok: Schema.Boolean }), failure: OrchestratorMcpFailure, @@ -1777,8 +1771,18 @@ it.effect("lists only read tools to a read-only client and still refuses its wri McpInvocationContext.McpInvocationContext, ThreadManagementService.ThreadManagementService, ], + }); + const AccessToolkit = Toolkit.make( + Tool.make("peek", { + description: "Reads.", + success: Schema.Struct({ ok: Schema.Boolean }), + failure: OrchestratorMcpFailure, + failureMode: "return", }), + writeTool("poke"), ); + // A second registration, so each toolkit's own writes must be hidden. + const OtherToolkit = Toolkit.make(writeTool("shove")); const scopeFor = ( token: string, access: "read-only" | "auto", @@ -1791,12 +1795,20 @@ it.effect("lists only read tools to a read-only client and still refuses its wri issuedAt: 1, }); const serverLayer = McpHttpServer.layerMcpTransport( - McpHttpServer.toolkitRegistration( - AccessToolkit, - McpToolAccess.toLayer(AccessToolkit, { - peek: McpToolAccess.reads(() => Effect.succeed({ ok: true })), - poke: McpToolAccess.writes(() => Effect.succeed({ ok: true })), - }), + Layer.mergeAll( + McpHttpServer.toolkitRegistration( + AccessToolkit, + McpToolAccess.toLayer(AccessToolkit, { + peek: McpToolAccess.reads(() => Effect.succeed({ ok: true })), + poke: McpToolAccess.writes(() => Effect.succeed({ ok: true })), + }), + ), + McpHttpServer.toolkitRegistration( + OtherToolkit, + McpToolAccess.toLayer(OtherToolkit, { + shove: McpToolAccess.writes(() => Effect.succeed({ ok: true })), + }), + ), ), ).pipe( Layer.provide(ServerSettings.layerTest()), @@ -1866,7 +1878,7 @@ it.effect("lists only read tools to a read-only client and still refuses its wri }); const operator = yield* session("operator"); - expect(names(yield* operator("tools/list", {}))).toEqual(["peek", "poke"]); + expect(names(yield* operator("tools/list", {}))).toEqual(["peek", "poke", "shove"]); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 124162d41732d..4db20a01a9ae9 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1261,18 +1261,22 @@ const provideRegistrationServices = () => ), ); -/** Calls are still answered by the handler, which refuses them; only discovery changes. */ -const hiddenFromReadOnlyClients = McpServer.visibility( - Effect.gen(function* () { - const hidden = yield* McpToolAccess.ReadOnlyHiddenTools; - // Untraced: it runs once per tool on every list request. - return Effect.fnUntraced(function* ({ method, target }: McpServer.MiddlewareOptions) { - if (method !== "tools/list" || !hidden.has(target)) return true; - const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); - return Option.getOrUndefined(scope)?.client?.access !== "read-only"; - }); - }), -); +/** + * Calls are still answered by the handler, which refuses them; only discovery changes. + * A function: layers memoize by identity, so a shared one would keep the first toolkit's names. + */ +const hiddenFromReadOnlyClients = () => + McpServer.visibility( + Effect.gen(function* () { + const hidden = yield* McpToolAccess.ReadOnlyHiddenTools; + // Untraced: it runs once per tool on every list request. + return Effect.fnUntraced(function* ({ method, target }: McpServer.MiddlewareOptions) { + if (method !== "tools/list" || !hidden.has(target)) return true; + const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); + return Option.getOrUndefined(scope)?.client?.access !== "read-only"; + }); + }), + ); /** * Tools declare their handler services as request-level dependencies. Those @@ -1296,7 +1300,7 @@ export const toolkitRegistration = , EX, >().layer, ), Layer.provide(McpServer.McpServer.layer), - Layer.provide(hiddenFromReadOnlyClients.layer), + Layer.provide(hiddenFromReadOnlyClients().layer), Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), );