Skip to content
Draft
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
11 changes: 0 additions & 11 deletions shared/glean/mcp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import {
fetchAllowedRemoteTools,
type DispatchContext,
} from "./tools/remote-passthrough.js";
import { resolveSessionId } from "./session-id.js";
import { serverDataDir } from "./data-dir.js";
import { resolveServerUrlFromEmail } from "./config-search.js";
import { pluginVersionString } from "./version.js";
Expand Down Expand Up @@ -376,7 +375,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
remoteClient = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
`tools-list-${process.pid}`,
);
} catch (err) {
// Auth expired mid-session, network blip, schema parse error — serve
Expand Down Expand Up @@ -458,7 +456,6 @@ async function connectWithSignIn(
const client = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
`setup-${process.pid}`,
);
return { ok: true, client };
} catch (err) {
Expand Down Expand Up @@ -495,7 +492,6 @@ async function connectWithSignIn(
const client = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
`setup-${process.pid}`,
);
// Unexpectedly connected without needing auth — done.
return { ok: true, client };
Expand Down Expand Up @@ -537,7 +533,6 @@ async function connectWithSignIn(
const client = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
`setup-${process.pid}`,
);
return { ok: true, client };
} catch (err) {
Expand Down Expand Up @@ -678,16 +673,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
};
}

const sessionId = resolveSessionId();

const skillsBaseDir = resolveSkillsBaseDir();

let remoteClient;
try {
remoteClient = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
sessionId,
);
} catch (err) {
if (err instanceof AuthRequiredError) {
Expand Down Expand Up @@ -744,14 +736,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
};
}

const sessionId = resolveSessionId();

let remoteClient;
try {
remoteClient = await createRemoteClient(
serverUrl,
await getRemoteClientOpts(),
sessionId,
);
} catch (err) {
if (err instanceof AuthRequiredError) {
Expand Down
74 changes: 9 additions & 65 deletions shared/glean/mcp/src/remote-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import type { GleanOAuthClientProvider } from "./auth-provider.js";
import { pluginVersionString } from "./version.js";
import { negotiationMeta, recordPolicyFromResult } from "./policy/session.js";

const GLEAN_PLUGIN = "GLEAN_PLUGIN";

// The MCP SDK applies DEFAULT_REQUEST_TIMEOUT_MSEC (60s) to every request when
// callTool is invoked without an explicit timeout. Downstream Glean tools can
// legitimately take longer than 60s, so we override the per-call timeout.
Expand All @@ -30,55 +28,6 @@ export function remoteToolTimeoutMs(): number {
: DEFAULT_REMOTE_TOOL_TIMEOUT_MS;
}

function encodeVarint(value: number): number[] {
const bytes: number[] = [];
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value >>>= 7;
}
bytes.push(value);
return bytes;
}

function encodeStringField(fieldNumber: number, value: string): number[] {
if (!value) return [];
const encoded = new TextEncoder().encode(value);
const tag = (fieldNumber << 3) | 2;
return [tag, ...encodeVarint(encoded.length), ...encoded];
}

function encodeMessageField(fieldNumber: number, inner: number[]): number[] {
const tag = (fieldNumber << 3) | 2;
return [tag, ...encodeVarint(inner.length), ...inner];
}

// Hand-rolled proto encoder for mcp.GatewayRequestMetadata. We don't currently
// have proto bindings in this repo, so the shape is hardcoded here. Cross-
// language parity is enforced by tests/remote-client.test.ts (byte-equality
// against the Go proto.Marshal output captured in scio's
// proxy_tools_provider_test.go::TestPluginGatewayRequestMetadata_NoSession).
//
// Proto layout (keep in sync with go/core/api/mcp/api.proto):
// workflow_id = field 1 (string)
// chat_session_id = field 2 (string)
// source_info = field 4 (core.SourceInfo)
// platform = field 2 (string)
// client_initiator = field 3 (string)
export function buildGatewayMetadataHeader(chatSessionId?: string): string {
const sourceInfo = [
...encodeStringField(2, GLEAN_PLUGIN),
...encodeStringField(3, GLEAN_PLUGIN),
];

const message = [
...encodeStringField(1, GLEAN_PLUGIN),
...(chatSessionId ? encodeStringField(2, chatSessionId) : []),
...encodeMessageField(4, sourceInfo),
];

return Buffer.from(new Uint8Array(message)).toString("base64");
}

function loggingFetch(
input: string | URL | Request,
init?: RequestInit,
Expand Down Expand Up @@ -150,16 +99,12 @@ function withConnectLock<T>(fn: () => Promise<T>): Promise<T> {
function buildTransport(
serverUrl: string,
opts: RemoteClientOptions,
chatSessionId?: string,
): StreamableHTTPClientTransport {
const parsedUrl = new URL(serverUrl);
// External clients must not send Glean internal-service headers; the edge WAF rejects them.
const headers: Record<string, string> = {
"X-Glean-Gateway-Request-Metadata": buildGatewayMetadataHeader(chatSessionId),
};

// Send no X-Glean-* request header. Glean ignored the gateway metadata
// header this client used to send, and Glean's edge can reject a request
// from outside that carries one of its internal headers.
const transportOpts: ConstructorParameters<typeof StreamableHTTPClientTransport>[1] = {
requestInit: { headers },
fetch: opts.fetch ?? loggingFetch,
};

Expand All @@ -173,7 +118,6 @@ function buildTransport(
export async function createRemoteClient(
serverUrl: string,
opts: RemoteClientOptions,
chatSessionId?: string,
authRetry = false,
): Promise<Client> {
const authProvider = opts.authProvider;
Expand All @@ -188,7 +132,7 @@ export async function createRemoteClient(
// Build a fresh transport for the exchange.
if (authProvider?.pendingAuthCode) {
const transportForAuth =
pendingTransport ?? buildTransport(serverUrl, opts, chatSessionId);
pendingTransport ?? buildTransport(serverUrl, opts);
console.error("[auth] Auth code received, exchanging for tokens...");
try {
await withConnectLock(() =>
Expand All @@ -197,14 +141,14 @@ export async function createRemoteClient(
authProvider.clearPendingAuth();
pendingTransport = undefined;
console.error("[auth] Token exchange complete, reconnecting...");
return createRemoteClient(serverUrl, opts, chatSessionId);
return createRemoteClient(serverUrl, opts);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(`[auth] Code exchange failed: ${msg} — discarding stale auth state`);
authProvider.clearPendingAuth();
pendingTransport = undefined;
await authProvider.invalidateCredentials("all");
return createRemoteClient(serverUrl, opts, chatSessionId);
return createRemoteClient(serverUrl, opts);
}
}

Expand Down Expand Up @@ -246,7 +190,7 @@ export async function createRemoteClient(
// Snapshot to detect a sibling's refresh between connect and failure.
const accessTokenAtConnect = authProvider?.tokens()?.access_token;

const transport = buildTransport(serverUrl, opts, chatSessionId);
const transport = buildTransport(serverUrl, opts);

try {
await withConnectLock(() => client.connect(transport));
Expand All @@ -266,7 +210,7 @@ export async function createRemoteClient(
"[auth] Auth failed but a newer token is on disk " +
"(sibling refresh) — retrying once",
);
return createRemoteClient(serverUrl, opts, chatSessionId, true);
return createRemoteClient(serverUrl, opts, true);
}
if (authProvider.authorizationUrl) {
pendingTransport = transport;
Expand All @@ -284,7 +228,7 @@ export async function createRemoteClient(
console.error(
"[auth] Refresh failed but a sibling refreshed — retrying with its token",
);
return createRemoteClient(serverUrl, opts, chatSessionId, true);
return createRemoteClient(serverUrl, opts, true);
}
throw error;
}
Expand Down
1 change: 0 additions & 1 deletion shared/glean/mcp/tests/remote-client-auth-retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ describe("createRemoteClient sibling-refresh retry", () => {
const client = await createRemoteClient(
serverUrl,
{ authProvider: provider },
"sess-1",
);

expect(client).toBeTruthy();
Expand Down
67 changes: 7 additions & 60 deletions shared/glean/mcp/tests/remote-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,66 +10,11 @@ import {
} from "@modelcontextprotocol/server";
import * as z from "zod/v4";
import {
buildGatewayMetadataHeader,
callRemoteTool,
createRemoteClient,
remoteToolTimeoutMs,
} from "../src/remote-client.js";

describe("buildGatewayMetadataHeader", () => {
it("produces stable output without session ID", () => {
const a = buildGatewayMetadataHeader();
const b = buildGatewayMetadataHeader();
expect(a).toBe(b);
expect(a.length).toBeGreaterThan(0);
});

it("produces different output with session ID", () => {
const without = buildGatewayMetadataHeader();
const with1 = buildGatewayMetadataHeader("session-abc");
const with2 = buildGatewayMetadataHeader("session-xyz");
expect(with1).not.toBe(without);
expect(with1).not.toBe(with2);
});

it("output is valid base64", () => {
const header = buildGatewayMetadataHeader("test-session");
const decoded = Buffer.from(header, "base64");
expect(decoded.length).toBeGreaterThan(0);
expect(Buffer.from(decoded).toString("base64")).toBe(header);
});

it("encodes workflow_id and source_info without session", () => {
const header = buildGatewayMetadataHeader();
const bytes = Buffer.from(header, "base64");

// The proto bytes should contain "GLEAN_PLUGIN" (workflow_id, platform,
// client_initiator) but no session ID string.
const content = bytes.toString("utf-8");
const matches = content.match(/GLEAN_PLUGIN/g);
expect(matches).not.toBeNull();
expect(matches!.length).toBe(3); // workflow_id + platform + client_initiator
});

// Cross-language parity: must match Go's proto.Marshal output captured in
// scio's go/core/mcp/server/proxy_tools_provider_test.go::
// TestPluginGatewayRequestMetadata_NoSession. If this constant drifts, the
// hand-rolled TS encoder has diverged from the proto schema — re-derive by
// running the Go test and copying the asserted base64 here.
it("matches Go proto.Marshal output (cross-language parity)", () => {
expect(buildGatewayMetadataHeader()).toBe(
"CgxHTEVBTl9QTFVHSU4iHBIMR0xFQU5fUExVR0lOGgxHTEVBTl9QTFVHSU4=",
);
});

it("encodes session ID into the proto bytes", () => {
const header = buildGatewayMetadataHeader("my-session-42");
const bytes = Buffer.from(header, "base64");
const content = bytes.toString("utf-8");
expect(content).toContain("my-session-42");
});
});

describe("remoteToolTimeoutMs", () => {
const KEY = "GLEAN_REMOTE_TOOL_TIMEOUT_MS";
const original = process.env[KEY];
Expand Down Expand Up @@ -213,7 +158,7 @@ describe("remote elicitation bridge", () => {
});

describe("remote transport headers", () => {
it("keeps gateway metadata without forwarding internal headers or removing sc", async () => {
it("sends no X-Glean-* header and keeps the sc query parameter", async () => {
const handler = createMcpHandler(
() => new McpServer({ name: "test", version: "1.0.0" }),
);
Expand All @@ -233,10 +178,12 @@ describe("remote transport headers", () => {
expect(requests.length).toBeGreaterThan(0);
for (const request of requests) {
expect(new URL(request.url).searchParams.get("sc")).toBe("request-scope");
expect(request.headers.has("X-Glean-Internal-Service")).toBe(false);
expect(request.headers.has("X-Glean-Request-ScParams")).toBe(false);
expect(request.headers.has("X-Glean-Forced-ScParams")).toBe(false);
expect(request.headers.has("X-Glean-Gateway-Request-Metadata")).toBe(true);
// Glean's edge can reject a request from outside that carries one of
// its internal headers, so the client sends none.
const gleanHeaders = [...request.headers.keys()].filter((name) =>
name.toLowerCase().startsWith("x-glean-"),
);
expect(gleanHeaders).toEqual([]);
}
} finally {
await client.close();
Expand Down
Loading