diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..9179ce22214ea 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -400,6 +400,47 @@ 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 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", + 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* () { 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/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e5d47410817f2..148ac2c103140 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1758,6 +1758,131 @@ 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 writeTool = (name: Name) => + Tool.make(name, { + description: "Writes.", + success: Schema.Struct({ ok: Schema.Boolean }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + 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", + ): McpInvocationContext.McpInvocationScope => ({ + environmentId, + requestNamespace: `client:${token}`, + thread: undefined, + client: { sessionId: token, label: "probe", access }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }); + const serverLayer = McpHttpServer.layerMcpTransport( + 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()), + 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", "shove"]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect( "lists watch tools only to threads that are not delegated children, and forge tools only where the project has a forge", () => diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 53d232aad842a..4db20a01a9ae9 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1261,6 +1261,23 @@ const provideRegistrationServices = () => ), ); +/** + * 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 * built with the server are provided here; `McpInvocationContext` is left to @@ -1283,6 +1300,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/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index cc7c1f6e219de..b29cf43acda3a 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -154,14 +154,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); @@ -260,8 +262,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/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index ed6be35c0c1ea..f4b1506c88075 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -65,8 +65,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 diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 826ffeb6b258e..3f78c86bf103b 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -611,6 +611,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; @@ -623,6 +624,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 }),