From de124b7a95a4a402326014f6f6cea1242e0e92ce Mon Sep 17 00:00:00 2001 From: Echways Date: Wed, 18 Nov 2026 00:21:15 +0300 Subject: [PATCH 1/6] fix(server): MCP OAuth grants no more than the scope the client asked for A client that asked for only orchestration:read was granted whatever access the approver picked, because the authorization request's scope was never read. The scope now travels with the request and caps the grant at read only when it names orchestration:read without orchestration:operate. The approval page disables the higher levels. --- apps/server/src/auth/McpOAuth.test.ts | 77 +++++++++++++++++++ apps/server/src/auth/McpOAuth.ts | 20 ++++- apps/server/src/auth/mcpOAuthHttp.ts | 7 +- .../components/auth/ConnectAgentSurface.tsx | 6 +- packages/contracts/src/auth.ts | 3 + 5 files changed, 106 insertions(+), 7 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..b69379ad5ac8e 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -753,6 +753,83 @@ it.effect( }), ); +it.live("a client that asks only for orchestration:read is granted read only access", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const signIn = (scope: string | undefined) => + Effect.gen(function* () { + const params = { + ...authorizeParams(clientId), + ...(scope === undefined ? {} : { scope }), + }; + const pairing = yield* auth.issuePairingCredential(); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "auto", + code: pairing.credential, + }); + const tokenResponse = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code: new URL(approved.redirectTo!).searchParams.get("code")!, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + resource: `${ORIGIN}/mcp`, + }), + ), + ); + const token = yield* json<{ access_token: string; scope: string }>(tokenResponse); + const client = yield* auth.authenticateMcpClient( + HttpServerRequest.fromWeb( + at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }), + ), + ); + return { scope: token.scope, access: client.access }; + }); + + expect(yield* signIn("orchestration:read")).toEqual({ + scope: "orchestration:read", + access: "read-only", + }); + expect(yield* signIn("orchestration:read orchestration:operate")).toEqual({ + scope: "orchestration:read orchestration:operate", + access: "auto", + }); + expect(yield* signIn("offline_access")).toMatchObject({ access: "auto" }); + expect(yield* signIn(undefined)).toMatchObject({ access: "auto" }); + + const readScoped = { ...authorizeParams(clientId), scope: "orchestration:read" }; + const pairing = yield* auth.issuePairingCredential(); + const cookie = (yield* handler( + at("/api/auth/browser-session", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ credential: pairing.credential }), + }), + )).headers + .getSetCookie()[0]! + .split(";", 1)[0]!; + const details = yield* handler(postJson("/oauth/mcp/approval", readScoped, cookie)).pipe( + Effect.flatMap( + json<{ csrfToken: string; oneClickAccess: ReadonlyArray; maxAccess?: string }>, + ), + ); + expect(details).toMatchObject({ oneClickAccess: ["read-only"], maxAccess: "read-only" }); + const approved = yield* decide( + handler, + readScoped, + { _tag: "browser-session", access: "full-access", csrfToken: details.csrfToken }, + cookie, + ); + expect(new URL(approved.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); + }), + ), +); + it.live("one-click approves only access the browser session holds the scopes for", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 18ad10c2dbd28..cec3793bdb653 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"; @@ -67,6 +67,14 @@ const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/; const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; +const requestedMaxAccess = (scope: string | undefined) => { + const requested = scope === undefined ? null : parseOAuthScope(scope); + return requested?.includes(AuthOrchestrationReadScope) && + !requested.includes(AuthOrchestrationOperateScope) + ? "read-only" + : undefined; +}; + export interface McpOAuthUrls { readonly issuer: string; readonly resource: string; @@ -186,6 +194,7 @@ export interface AuthorizationRequest { readonly state: Redacted.Redacted | undefined; readonly resource: string; readonly issuer: string; + readonly maxAccess: "read-only" | undefined; } interface PendingCode { @@ -420,6 +429,7 @@ const make = Effect.gen(function* () { state, resource: urls.resource, issuer: urls.issuer, + maxAccess: requestedMaxAccess(request.scope), } satisfies AuthorizationRequest; }); @@ -466,7 +476,8 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; - let access = decision.access; + const { maxAccess } = input.authorization; + let access = maxAccess ?? decision.access; if (decision._tag === "pairing-code") { // An approval code is for one app's sign-in, never for linking another environment. if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) { @@ -474,7 +485,7 @@ const make = Effect.gen(function* () { description: "Linking needs a plain pairing code, not an app approval code.", }); } - access = yield* environmentAuth + const approvedAccess = yield* environmentAuth .consumeMcpApprovalCode(decision.code, decision.access, input.authorization.client.peerLink) .pipe( Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => @@ -489,12 +500,13 @@ const make = Effect.gen(function* () { ), ), ); + access = maxAccess ?? approvedAccess; } else { const session = yield* approvingSession(input.request, input.authorization); if ( session === undefined || !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) || - !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope)) + !mcpClientScopes(access).every((scope) => session.scopes.includes(scope)) ) { return yield* new McpOAuthPageError({ description: "Your session cannot approve this request. Enter a pairing code instead.", diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 6e10362000adf..59ff75c03f071 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -173,6 +173,7 @@ export const layer = HttpApiBuilder.group( clientName: resolved.client.name, redirectHost: new URL(resolved.redirectUri).host, environmentHost: new URL(urls.issuer).host, + ...(resolved.maxAccess === undefined ? {} : { maxAccess: resolved.maxAccess }), ...(oauth.runtimeModeCeiling === undefined ? {} : { runtimeModeCeiling: oauth.runtimeModeCeiling }), @@ -180,8 +181,10 @@ export const layer = HttpApiBuilder.group( ? {} : { csrfToken: session.csrfToken, - oneClickAccess: AuthMcpClientAccess.literals.filter((access) => - mcpClientScopes(access).every((scope) => session.scopes.includes(scope)), + oneClickAccess: AuthMcpClientAccess.literals.filter( + (access) => + (resolved.maxAccess ?? access) === access && + mcpClientScopes(access).every((scope) => session.scopes.includes(scope)), ), }), }; diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index 9d03091433610..39a4ec7b34ed0 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -251,7 +251,8 @@ export function McpConsent({ 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; + const typedCodeAccess = parseMcpApprovalCode(pairingCode)?.access; + const codeAccess = typedCodeAccess && (details.maxAccess ?? typedCodeAccess); const approveLevel = codeAccess ?? access; return ( @@ -394,6 +395,9 @@ function ConnectAgentHeading({ /** Why a managed policy keeps `access` from being granted, or undefined when it may be. */ function ceilingReason(details: AuthMcpApprovalDetails, access: AuthMcpClientAccess) { + if (details.maxAccess !== undefined && access !== details.maxAccess) { + return "The app asked for read access only."; + } const ceiling = details.runtimeModeCeiling; return ceiling === undefined || access === "read-only" || diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 132cc7322337b..364ee897b2bc1 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)), + /** Set when the client asked for read access only, so no higher level can be granted. */ + maxAccess: 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 fe867d74b06e4af9c76a0c392d20735c569d8796 Mon Sep 17 00:00:00 2001 From: Echways Date: Wed, 18 Nov 2026 00:40:50 +0300 Subject: [PATCH 2/6] fix(web): MCP consent clamps access to the app's requested read-only scope --- apps/server/src/auth/McpOAuth.test.ts | 21 ++++++++++++++++++- .../auth/ConnectAgentSurface.logic.test.ts | 1 + .../auth/ConnectAgentSurface.logic.ts | 2 ++ .../components/auth/ConnectAgentSurface.tsx | 1 + 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index b69379ad5ac8e..e2dfe88f8cad1 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -825,7 +825,26 @@ it.live("a client that asks only for orchestration:read is granted read only acc { _tag: "browser-session", access: "full-access", csrfToken: details.csrfToken }, cookie, ); - expect(new URL(approved.redirectTo!).searchParams.get("code")).toEqual(expect.any(String)); + const browserToken = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code: new URL(approved.redirectTo!).searchParams.get("code")!, + redirect_uri: readScoped.redirect_uri, + client_id: clientId, + code_verifier: verifier, + resource: `${ORIGIN}/mcp`, + }), + ), + ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>)); + expect(browserToken.scope).toBe("orchestration:read"); + const browserClient = yield* auth.authenticateMcpClient( + HttpServerRequest.fromWeb( + at("/mcp", { headers: { authorization: `Bearer ${browserToken.access_token}` } }), + ), + ); + expect(browserClient.access).toBe("read-only"); }), ), ); diff --git a/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts b/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts index a7a0a05602d4c..9c4840cae263d 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts +++ b/apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts @@ -14,6 +14,7 @@ it.each(RuntimeMode.literals)("keeps MCP access within the %s policy ceiling", ( ); expect(resolveMcpAccess("read-only", ceiling, false)).toBe("read-only"); expect(resolveMcpAccess("approval-required", ceiling, false)).toBe("approval-required"); + expect(resolveMcpAccess(null, ceiling, true, "read-only")).toBe("read-only"); }); it("checks a typed code even in a signed-in browser, and approves without one at Read only", () => { diff --git a/apps/web/src/components/auth/ConnectAgentSurface.logic.ts b/apps/web/src/components/auth/ConnectAgentSurface.logic.ts index b796c6a55c85e..bab6fc1333aa8 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.logic.ts +++ b/apps/web/src/components/auth/ConnectAgentSurface.logic.ts @@ -15,7 +15,9 @@ export function resolveMcpAccess( requested: AuthMcpClientAccess | null, ceiling: AuthMcpApprovalDetails["runtimeModeCeiling"], hasCode: boolean, + maxAccess?: AuthMcpClientAccess, ): AuthMcpClientAccess { + if (maxAccess !== undefined) return maxAccess; const access = requested ?? (hasCode ? "auto" : "read-only"); return access !== "read-only" && ceiling !== undefined && diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index 39a4ec7b34ed0..7a5c9e9d55b9b 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -156,6 +156,7 @@ export function McpConsent({ requestedAccess, loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined, pairingCode.trim().length > 0, + loaded.status === "ready" ? loaded.details.maxAccess : undefined, ); const [errorMessage, setErrorMessage] = useState(""); const [pending, setPending] = useState<"approve" | "deny" | null>(null); From d41628afe4abd6c9cebdc983bf54b2286e6f30be Mon Sep 17 00:00:00 2001 From: Echways Date: Wed, 18 Nov 2026 00:41:37 +0300 Subject: [PATCH 3/6] test(server): in-process MCP OAuth read-scope test runs on the test clock --- apps/server/src/auth/McpOAuth.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index e2dfe88f8cad1..a92de89652e6f 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -753,7 +753,7 @@ it.effect( }), ); -it.live("a client that asks only for orchestration:read is granted read only access", () => +it.effect("a client that asks only for orchestration:read is granted read only access", () => withRoutes((handler, auth) => Effect.gen(function* () { const clientId = yield* registeredClientId(handler); From bc2f010cb963000bc283e93cc91dd737f3f51ba6 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 18 Nov 2026 10:51:53 +0000 Subject: [PATCH 4/6] fix(auth): align OAuth test clock and translate scope ceiling --- apps/server/src/auth/McpOAuth.test.ts | 6 +++++- apps/web/src/components/auth/ConnectAgentSurface.tsx | 2 +- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + 12 files changed, 16 insertions(+), 2 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index a92de89652e6f..baa8238096627 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -113,7 +113,10 @@ const withRoutes = ( ) => Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; - const context = Context.make(SecureRandom.SecureRandom, random); + const clock = yield* Clock.Clock; + const context = Context.make(SecureRandom.SecureRandom, random).pipe( + Context.add(Clock.Clock, clock), + ); let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined; const layerRoutes = makeLayerRoutes((auth) => { routerAuth = auth; @@ -769,6 +772,7 @@ it.effect("a client that asks only for orchestration:read is granted read only a access: "auto", code: pairing.credential, }); + expect(approved).toMatchObject({ status: 200, redirectTo: expect.any(String) }); const tokenResponse = yield* handler( at( "/oauth/mcp/token", diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx index fc81e8578e9e9..56388553ca29b 100644 --- a/apps/web/src/components/auth/ConnectAgentSurface.tsx +++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx @@ -444,7 +444,7 @@ function ceilingReason( resolve: MessageResolver, ) { if (details.maxAccess !== undefined && access !== details.maxAccess) { - return "The app asked for read access only."; + return resolve(msg("The app asked for read access only.")); } const ceiling = details.runtimeModeCeiling; return ceiling === undefined || diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4c9f0f6d27e4f..7f2bc894111dc 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2957,6 +2957,7 @@ "9c5a2e144cefdf2f": "Nur lesen", "12d03e02951725b0": "Projekte und Threads lesen. Kann nichts starten, keine Nachrichten senden und nichts ändern.", "b6c9bd4137eca7b1": "Die Umgebung hat eine Adresse zurückgegeben, die diese Seite nicht öffnet.", + "80fff23ff3c58f48": "Die App hat nur Lesezugriff angefordert.", "8ec8255ffc9fe8e9": "Die Anmeldung konnte nicht fortgesetzt werden.", "04358a5e0d679d69": "Anmeldeanfrage wird geprüft", "5decc5fd8dc3f6a7": "Einen Moment, diese Umgebung prüft die Anfrage des Agenten.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c40470b46e6ae..7562e1f844c09 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Read only", "12d03e02951725b0": "Read projects and threads. Cannot start, message or change anything.", "b6c9bd4137eca7b1": "The environment returned an address this page will not open.", + "80fff23ff3c58f48": "The app asked for read access only.", "8ec8255ffc9fe8e9": "The sign-in could not continue.", "04358a5e0d679d69": "Checking the sign-in request", "5decc5fd8dc3f6a7": "One moment while this environment verifies the agent's request.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 68f63f589f51e..a3f166732e79e 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Solo lectura", "12d03e02951725b0": "Leer proyectos e hilos. No puede iniciar, enviar mensajes ni cambiar nada.", "b6c9bd4137eca7b1": "El entorno devolvió una dirección que esta página no abrirá.", + "80fff23ff3c58f48": "La aplicación solo ha solicitado acceso de lectura.", "8ec8255ffc9fe8e9": "El inicio de sesión no pudo continuar.", "04358a5e0d679d69": "Comprobando la solicitud de inicio de sesión", "5decc5fd8dc3f6a7": "Un momento mientras este entorno verifica la solicitud del agente.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 442c22ed3a2d7..fb3f849ae6b21 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Lecture seule", "12d03e02951725b0": "Lire les projets et les fils. Ne peut rien démarrer, envoyer ni modifier.", "b6c9bd4137eca7b1": "L’environnement a renvoyé une adresse que cette page n’ouvrira pas.", + "80fff23ff3c58f48": "L'application a demandé un accès en lecture seule.", "8ec8255ffc9fe8e9": "La connexion n’a pas pu se poursuivre.", "04358a5e0d679d69": "Vérification de la demande de connexion", "5decc5fd8dc3f6a7": "Un instant, le temps que cet environnement vérifie la demande de l’agent.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c9417551b208c..bfc93ecae2d15 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2954,6 +2954,7 @@ "9c5a2e144cefdf2f": "読み取り専用", "12d03e02951725b0": "プロジェクトとスレッドを読み取ります。開始、メッセージ送信、変更はできません。", "b6c9bd4137eca7b1": "環境から、このページでは開けないアドレスが返されました。", + "80fff23ff3c58f48": "アプリは読み取りアクセスのみを要求しました。", "8ec8255ffc9fe8e9": "サインインを続行できませんでした。", "04358a5e0d679d69": "サインインリクエストを確認しています", "5decc5fd8dc3f6a7": "この環境がエージェントのリクエストを検証しています。しばらくお待ちください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 362d29d071a87..069342c939d75 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2955,6 +2955,7 @@ "9c5a2e144cefdf2f": "읽기 전용", "12d03e02951725b0": "프로젝트와 스레드를 읽습니다. 시작, 메시지 전송, 변경은 할 수 없습니다.", "b6c9bd4137eca7b1": "환경에서 이 페이지가 열지 않는 주소를 반환했습니다.", + "80fff23ff3c58f48": "앱이 읽기 전용 액세스만 요청했습니다。", "8ec8255ffc9fe8e9": "로그인을 계속할 수 없습니다.", "04358a5e0d679d69": "로그인 요청을 확인하는 중", "5decc5fd8dc3f6a7": "이 환경에서 에이전트의 요청을 확인하는 동안 잠시 기다려 주세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index b598943e92383..d4a9abe4ee840 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Somente leitura", "12d03e02951725b0": "Lê projetos e threads. Não pode iniciar, enviar mensagens nem alterar nada.", "b6c9bd4137eca7b1": "O ambiente retornou um endereço que esta página não vai abrir.", + "80fff23ff3c58f48": "O aplicativo solicitou apenas acesso de leitura.", "8ec8255ffc9fe8e9": "Não foi possível continuar o login.", "04358a5e0d679d69": "Verificando a solicitação de login", "5decc5fd8dc3f6a7": "Um momento enquanto este ambiente verifica a solicitação do agente.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index a8a54a6500e59..f4e6e2504af4b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Только чтение", "12d03e02951725b0": "Чтение проектов и тредов. Нельзя ничего запускать, отправлять или менять.", "b6c9bd4137eca7b1": "Окружение вернуло адрес, который эта страница не откроет.", + "80fff23ff3c58f48": "Приложение запросило только доступ для чтения.", "8ec8255ffc9fe8e9": "Не удалось продолжить вход.", "04358a5e0d679d69": "Проверка запроса на вход", "5decc5fd8dc3f6a7": "Подождите, окружение проверяет запрос агента.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index adaf8566b6411..492b62832b04b 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2956,6 +2956,7 @@ "9c5a2e144cefdf2f": "Endast läsning", "12d03e02951725b0": "Läs projekt och trådar. Kan inte starta, skicka meddelanden eller ändra något.", "b6c9bd4137eca7b1": "Miljön returnerade en adress som den här sidan inte öppnar.", + "80fff23ff3c58f48": "Appen begärde endast läsåtkomst.", "8ec8255ffc9fe8e9": "Inloggningen kunde inte fortsätta.", "04358a5e0d679d69": "Kontrollerar inloggningsbegäran", "5decc5fd8dc3f6a7": "Ett ögonblick medan den här miljön verifierar agentens begäran.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index f386e717a0614..639bcdeac3923 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2960,6 +2960,7 @@ "9c5a2e144cefdf2f": "只读", "12d03e02951725b0": "读取项目和会话,不能启动会话、发送消息或进行任何更改。", "b6c9bd4137eca7b1": "环境返回了一个此页面不会打开的地址。", + "80fff23ff3c58f48": "该应用仅请求读取权限。", "8ec8255ffc9fe8e9": "无法继续登录。", "04358a5e0d679d69": "正在检查登录请求", "5decc5fd8dc3f6a7": "请稍候,此环境正在验证智能体的请求。", From acd28f9ae9b7c5e59a6b69e2fadbd4ccc8a6cadf Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 18 Nov 2026 13:28:24 +0000 Subject: [PATCH 5/6] fix(auth): hide write-only tools from read-only mcp clients --- apps/server/src/mcp/McpHttpServer.test.ts | 35 +++++++++++++++++-- apps/server/src/mcp/McpHttpServer.ts | 11 ++++++ apps/server/src/mcp/McpToolAccess.ts | 42 ++++++++++++++++++++--- 3 files changed, 81 insertions(+), 7 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 761991fd48769..78e0a4ff8e4d3 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1978,12 +1978,18 @@ it.effect("lists optional tools to a deferring client only after tool_search loa ["deferringToken", scopeFor("deferringToken")], ["otherToken", scopeFor("otherToken")], ]); + const parameters = Schema.Struct({ write: Schema.optional(Schema.Boolean) }); const tool = (name: string, description: string) => Tool.make(name, { description, + parameters, success: Schema.Struct({}), failure: OrchestratorMcpFailure, failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ], }); const OptionalToolkit = Toolkit.make( tool("delegate_task", "Delegates a task."), @@ -1991,14 +1997,15 @@ it.effect("lists optional tools to a deferring client only after tool_search loa tool("schedule_task", "Schedules a task."), ); const reads = McpToolAccess.reads(() => Effect.succeed({})); + const writes = McpToolAccess.writes((_input: typeof parameters.Type) => Effect.succeed({})); const serverLayer = McpHttpServer.layerMcpTransport( Layer.mergeAll( McpHttpServer.toolkitRegistration( OptionalToolkit, McpToolAccess.toLayer(OptionalToolkit, { - delegate_task: reads, + delegate_task: writes, preview_open: reads, - schedule_task: reads, + schedule_task: McpToolAccess.either((input) => input.write === true, writes, reads), }), ), McpHttpServer.layerToolSearch, @@ -2006,6 +2013,23 @@ it.effect("lists optional tools to a deferring client only after tool_search loa ).pipe( Layer.provide(ServerSettings.layerTest()), Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.succeed(McpHttpServer.McpClientAuthenticator, { + authenticate: (request) => + Effect.succeed( + request.headers.authorization === "Bearer read.only" + ? { + environmentId, + requestNamespace: "client:read-only", + thread: undefined, + client: { sessionId: "read-only", label: "Reader", access: "read-only" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + } + : undefined, + ), + }), + ), Layer.provide( Layer.mock(McpSessionRegistry.McpSessionRegistry)({ resolve: (token) => Effect.succeed(scopes.get(token)), @@ -2073,6 +2097,13 @@ it.effect("lists optional tools to a deferring client only after tool_search loa const other = yield* session("otherToken", false); expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]); expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]); + const readOnly = yield* session("read.only", false); + expect(yield* readOnly.listed).toEqual(["preview_open", "schedule_task"]); + expect((yield* readOnly.call("schedule_task", {})).structuredContent).toEqual({}); + expect(yield* readOnly.call("schedule_task", { write: true })).toMatchObject({ + isError: true, + }); + expect(yield* readOnly.call("delegate_task", {})).toMatchObject({ isError: true }); // Unlisted tools stay callable. expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({}); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 9a85e5e01f3c5..23888567c2ac5 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1218,6 +1218,17 @@ export const toolkitRegistration = , EX, ), ), ).pipe( + Layer.provide( + McpServer.visibility(({ method, target }) => + Effect.map( + Effect.serviceOption(McpInvocationContext.McpInvocationContext), + (scope) => + method !== "tools/list" || + Option.getOrUndefined(scope)?.client?.access !== "read-only" || + McpToolAccess.HandlersLayer.isReadable(handlers, target), + ), + ).layer, + ), Layer.provide( provideRegistrationServices< Exclude, McpInvocationContext.McpInvocationContext> diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 20a9274798d0f..db42cd52beec3 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -49,6 +49,7 @@ let declare: ( handle: (params: P) => Effect.Effect, remote: RemoteCheck

| undefined, forwarded?: Forwarded, + readable?: boolean, ) => Declaration<(params: P) => Effect.Effect>; /** @@ -81,10 +82,12 @@ let checkedHandler: CheckedHandler; let handlersLayer: , EX, RX>( layer: Layer.Layer, EX, RX>, + readableTools: ReadonlySet, ) => HandlersLayer; /** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */ export class Declaration { + readonly readable: boolean; readonly #handle: Handler; readonly #remote: RemoteCheck | undefined; readonly #forwarded: Forwarded | undefined; @@ -93,19 +96,22 @@ export class Declaration { handle: Handler, remote: RemoteCheck | undefined, forwarded: Forwarded | undefined, + readable: boolean, ) { refuseOutsideConstruction(token); this.#handle = handle; this.#remote = remote; this.#forwarded = forwarded; + this.readable = readable; } static { - declare = (handle, remote, forwarded) => + declare = (handle, remote, forwarded, readable = false) => new Declaration( builtHere, handle, remote, forwarded as Forwarded | undefined, + readable, ); checkedHandler = Struct.lambda((declaration) => declaration.#handle); remoteCheckOf = (declaration) => declaration.#remote; @@ -145,10 +151,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 +314,8 @@ export const either = ( message: "This action acts as the calling thread, which is here. Omit environmentId.", }), ), + undefined, + first.readable || second.readable, ); }; @@ -316,6 +331,7 @@ export const afterForwarding = ( checkedHandler(declaration) as (params: P) => Effect.Effect, remoteCheckOf(declaration) as RemoteCheck

| undefined, forwarded, + declaration.readable, ); const fullAccessRequired = @@ -367,21 +383,30 @@ export type Handlers> = Declarations< export class HandlersLayer, EX = never, RX = never> { readonly #layer: Layer.Layer, EX, RX>; + readonly #readableTools: ReadonlySet; private constructor( token: typeof builtHere, layer: Layer.Layer, EX, RX>, + readableTools: ReadonlySet, ) { refuseOutsideConstruction(token); this.#layer = layer; + this.#readableTools = readableTools; } static { - handlersLayer = (layer) => new HandlersLayer(builtHere, layer); + handlersLayer = (layer, readableTools) => new HandlersLayer(builtHere, layer, readableTools); } static layer, EX, RX>( handlers: HandlersLayer, ) { return handlers.#layer; } + static isReadable, EX, RX>( + handlers: HandlersLayer, + name: string, + ) { + return handlers.#readableTools.has(name); + } } const checkedHandlers = (declarations: Declarations): Handlers => @@ -465,12 +490,19 @@ export const toLayer = , EX = never, RX = toolkit: Toolkit.Toolkit, build: Handlers | Effect.Effect, EX, RX>, ): HandlersLayer> => { + const readableTools = new Set(); // Checked as soon as they are given, so a forged declaration fails here. - const withDeclarations = (declarations: Handlers) => - routed(toolkit, declarations, checkedHandlers(declarations)); + const withDeclarations = (declarations: Handlers) => { + const checked = checkedHandlers(declarations); + for (const [name, declaration] of Object.entries>(declarations)) { + if (declaration.readable) readableTools.add(name); + } + return routed(toolkit, declarations, checked); + }; return handlersLayer( toolkit.toLayer( Effect.isEffect(build) ? Effect.flatMap(build, withDeclarations) : withDeclarations(build), ), + readableTools, ); }; From c1857c261b18425211f6dc267ed7cddd979ac6e2 Mon Sep 17 00:00:00 2001 From: Echways Date: Thu, 19 Nov 2026 22:48:38 +0300 Subject: [PATCH 6/6] test(mcp): assert read-only write denial codes --- apps/server/src/mcp/McpHttpServer.test.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 78e0a4ff8e4d3..3138eafb8cdd0 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -2088,7 +2088,7 @@ it.effect("lists optional tools to a deferring client only after tool_search loa ), call: (name: string, args: object) => rpc("tools/call", { name, arguments: args }).pipe( - Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result), + Effect.map((body) => (body as { result: McpSchema.CallToolResult }).result), ), }; }); @@ -2100,10 +2100,18 @@ it.effect("lists optional tools to a deferring client only after tool_search loa const readOnly = yield* session("read.only", false); expect(yield* readOnly.listed).toEqual(["preview_open", "schedule_task"]); expect((yield* readOnly.call("schedule_task", {})).structuredContent).toEqual({}); - expect(yield* readOnly.call("schedule_task", { write: true })).toMatchObject({ - isError: true, - }); - expect(yield* readOnly.call("delegate_task", {})).toMatchObject({ isError: true }); + for (const [name, args] of [ + ["schedule_task", { write: true }], + ["delegate_task", {}], + ] as const) { + const result = yield* readOnly.call(name, args); + const content = result.content[0]; + expect(result.isError, name).toBe(true); + expect( + content?.type === "text" ? decodeJsonText(content.text) : undefined, + name, + ).toMatchObject({ code: "capability_denied" }); + } // Unlisted tools stay callable. expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});