Skip to content
Open
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
41 changes: 41 additions & 0 deletions apps/server/src/auth/McpOAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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* () {
Expand Down
11 changes: 10 additions & 1 deletion apps/server/src/auth/McpOAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -186,6 +186,8 @@ export interface AuthorizationRequest {
readonly state: Redacted.Redacted<string> | undefined;
readonly resource: string;
readonly issuer: string;
/** The client requested `orchestration:read` without `orchestration:operate`. */
readonly readOnly: boolean;
}

interface PendingCode {
Expand Down Expand Up @@ -413,13 +415,18 @@ 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,
codeChallenge,
state,
resource: urls.resource,
issuer: urls.issuer,
readOnly:
requestedScopes !== null &&
requestedScopes.includes(AuthOrchestrationReadScope) &&
!requestedScopes.includes(AuthOrchestrationOperateScope),
} satisfies AuthorizationRequest;
});

Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/mcpOAuthHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ export const layer = HttpApiBuilder.group(
...(oauth.runtimeModeCeiling === undefined
? {}
: { runtimeModeCeiling: oauth.runtimeModeCeiling }),
...(resolved.readOnly ? { requestedAccess: "read-only" as const } : {}),
...(session === undefined
? {}
: {
Expand Down
125 changes: 125 additions & 0 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <const Name extends string>(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<string, unknown> }).result),
);
});
const names = (result: Record<string, unknown>) =>
(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",
() =>
Expand Down
18 changes: 18 additions & 0 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1261,6 +1261,23 @@ const provideRegistrationServices = <Services>() =>
),
);

/**
* 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
Expand All @@ -1283,6 +1300,7 @@ export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX,
>().layer,
),
Layer.provide(McpServer.McpServer.layer),
Layer.provide(hiddenFromReadOnlyClients().layer),
Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
);

Expand Down
Loading
Loading