diff --git a/packages/sdk/src/auth.ts b/packages/sdk/src/auth.ts index c9605ab6..84f77352 100644 --- a/packages/sdk/src/auth.ts +++ b/packages/sdk/src/auth.ts @@ -20,6 +20,10 @@ * logic so both code paths stay in sync. */ +import { SDK_VERSION } from "./version.js"; + +export type ClientSurface = "sdk" | "mcp" | "cli"; + export interface AuthHeaderOptions { apiKey?: string; accessToken?: string; @@ -27,6 +31,47 @@ export interface AuthHeaderOptions { quotaProjectId?: string; } +/** + * Build the Google API client telemetry header identifying the Stitch SDK + * version and top-level client surface (`gccl/ client/`). + */ +export function buildClientSurfaceHeader( + surface: ClientSurface = "sdk", +): string { + return `gccl/${SDK_VERSION} client/${surface}`; +} + +/** + * Merge HTTP headers case-insensitively. When an override matches an existing + * header name regardless of casing, the earlier entry is replaced cleanly so + * mixed-case duplicate keys cannot reach `fetch` or MCP transports. + */ +export function mergeHeadersCaseInsensitive( + base: Record, + overrides?: Record, +): Record { + const merged: Record = {}; + const keyByLower = new Map(); + + const apply = (source: Record) => { + for (const [key, value] of Object.entries(source)) { + const lower = key.toLowerCase(); + const existingKey = keyByLower.get(lower); + if (existingKey !== undefined && existingKey !== key) { + delete merged[existingKey]; + } + keyByLower.set(lower, key); + merged[key] = value; + } + }; + + apply(base); + if (overrides) { + apply(overrides); + } + return merged; +} + /** * Build auth headers for a Stitch API request. * diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 9df4c5d3..0378fad3 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -27,7 +27,11 @@ import { } from "./spec/client.js"; import { StitchError } from "./spec/errors.js"; import { classifyError, isRecoverable } from "./spec/error-mapping.js"; -import { buildAuthHeaders as buildBaseAuthHeaders } from "./auth.js"; +import { + buildAuthHeaders as buildBaseAuthHeaders, + buildClientSurfaceHeader, + mergeHeadersCaseInsensitive, +} from "./auth.js"; import { SDK_VERSION } from "./version.js"; import { repairToolSchemas } from "./schema-repair.js"; import { EntityManager } from "./entity-manager.js"; @@ -87,6 +91,7 @@ export function resolveConfigWithEnv( env("GOOGLE_CLOUD_PROJECT"), baseUrl, timeout: input?.timeout, + headers: input?.headers, retry: input?.retry, entityCache: input?.entityCache, }; @@ -299,17 +304,21 @@ export class StitchToolClient implements StitchToolClientSpec { } /** - * Build auth headers based on config (API key or OAuth). + * Build auth and client identification headers based on config. */ private buildAuthHeaders(): Record { - return { - Accept: "application/json, text/event-stream", - ...buildBaseAuthHeaders({ - apiKey: this.config.apiKey, - accessToken: this.config.accessToken, - quotaProjectId: this.config.projectId, - }), - }; + return mergeHeadersCaseInsensitive( + { + Accept: "application/json, text/event-stream", + "X-Goog-Api-Client": buildClientSurfaceHeader("sdk"), + ...buildBaseAuthHeaders({ + apiKey: this.config.apiKey, + accessToken: this.config.accessToken, + quotaProjectId: this.config.projectId, + }), + }, + this.config.headers, + ); } private parseToolResponse(result: any, name: string): T { @@ -482,10 +491,9 @@ export class StitchToolClient implements StitchToolClientSpec { const url = `${this.config.baseUrl.replace(/\/mcp$/, "").replace(/\/$/, "")}/v1/${path}`; const response = await fetch(url, { method: "POST", - headers: { - ...this.buildAuthHeaders(), + headers: mergeHeadersCaseInsensitive(this.buildAuthHeaders(), { "Content-Type": "application/json", - }, + }), body: JSON.stringify(body), }); diff --git a/packages/sdk/src/proxy/core.ts b/packages/sdk/src/proxy/core.ts index c309ee6b..cf66adbd 100644 --- a/packages/sdk/src/proxy/core.ts +++ b/packages/sdk/src/proxy/core.ts @@ -20,6 +20,10 @@ import { StitchProxyConfig, StitchProxySpec, } from "../spec/proxy.js"; +import { + buildClientSurfaceHeader, + mergeHeadersCaseInsensitive, +} from "../auth.js"; import { StitchToolClient } from "../client.js"; import { ProxyContext, initializeStitchConnection } from "./client.js"; import { registerListToolsHandler } from "./handlers/listTools.js"; @@ -52,6 +56,7 @@ export class StitchProxy implements StitchProxySpec { process.env.STITCH_MCP_URL, name: inputConfig?.name, version: inputConfig?.version, + headers: inputConfig?.headers, }; // Validate config @@ -85,6 +90,10 @@ export class StitchProxy implements StitchProxySpec { accessToken: this.config.accessToken, projectId: this.config.quotaProjectId, baseUrl: this.config.url, + headers: mergeHeadersCaseInsensitive( + { "X-Goog-Api-Client": buildClientSurfaceHeader("mcp") }, + this.config.headers, + ), }), remoteTools: [] as Tool[], }; diff --git a/packages/sdk/src/singleton.ts b/packages/sdk/src/singleton.ts index 060ffb84..1d0058ef 100644 --- a/packages/sdk/src/singleton.ts +++ b/packages/sdk/src/singleton.ts @@ -23,6 +23,7 @@ export interface SingletonClientConfig { projectId?: string; baseUrl?: string; timeout?: number; + headers?: Record; retry?: StitchConfig["retry"]; entityCache?: boolean; } @@ -50,16 +51,21 @@ function resolveAndKey(config?: SingletonClientConfig): { projectId: config?.projectId, baseUrl: config?.baseUrl, timeout: config?.timeout, + headers: config?.headers, retry: config?.retry, entityCache: config?.entityCache, }), ); + const sortedHeaders = resolved.headers + ? Object.entries(resolved.headers).sort(([a], [b]) => a.localeCompare(b)) + : undefined; const key = JSON.stringify({ apiKey: resolved.apiKey, accessToken: resolved.accessToken, projectId: resolved.projectId, baseUrl: resolved.baseUrl, timeout: resolved.timeout, + headers: sortedHeaders, retry: resolved.retry, entityCache: resolved.entityCache, }); diff --git a/packages/sdk/src/spec/client.ts b/packages/sdk/src/spec/client.ts index 546ec59b..f189f48b 100644 --- a/packages/sdk/src/spec/client.ts +++ b/packages/sdk/src/spec/client.ts @@ -35,6 +35,12 @@ export const StitchConfigSchema = z /** Request timeout in milliseconds. Default: 300000 (5 min). */ timeout: z.number().default(300_000), + /** + * Additional HTTP headers merged case-insensitively onto outbound MCP and + * REST requests (for example, overriding `X-Goog-Api-Client`). + */ + headers: z.record(z.string(), z.string()).optional(), + /** * Identity-map toggle. Default true: resolving the same entity * yields the same instance (with data merged on refresh). Set false diff --git a/packages/sdk/src/spec/proxy.ts b/packages/sdk/src/spec/proxy.ts index f21d6f2b..a5e9618d 100644 --- a/packages/sdk/src/spec/proxy.ts +++ b/packages/sdk/src/spec/proxy.ts @@ -41,6 +41,9 @@ export const StitchProxyConfigSchema = z /** Protocol version to use for Stitch JSON-RPC connection. Default: '2025-06-18' */ protocolVersion: z.string().default("2025-06-18"), + + /** Additional HTTP headers merged case-insensitively onto upstream Stitch requests. */ + headers: z.record(z.string(), z.string()).optional(), }) .refine((data) => !data.accessToken || data.apiKey || !!data.quotaProjectId, { // Aligned with StitchConfigSchema: token auth needs a quota project. diff --git a/packages/sdk/test/unit/auth.test.ts b/packages/sdk/test/unit/auth.test.ts index 4aa90c94..b2ada6ac 100644 --- a/packages/sdk/test/unit/auth.test.ts +++ b/packages/sdk/test/unit/auth.test.ts @@ -13,7 +13,12 @@ // limitations under the License. import { describe, it, expect } from "vitest"; -import { buildAuthHeaders } from "../../src/auth.js"; +import { + buildAuthHeaders, + buildClientSurfaceHeader, + mergeHeadersCaseInsensitive, +} from "../../src/auth.js"; +import { SDK_VERSION } from "../../src/version.js"; describe("buildAuthHeaders", () => { it("emits X-Goog-Api-Key for an API key", () => { @@ -40,3 +45,46 @@ describe("buildAuthHeaders", () => { ); }); }); + +describe("buildClientSurfaceHeader", () => { + it("defaults to sdk client surface with SDK_VERSION", () => { + expect(buildClientSurfaceHeader()).toBe(`gccl/${SDK_VERSION} client/sdk`); + }); + + it("formats mcp and cli surfaces explicitly", () => { + expect(buildClientSurfaceHeader("mcp")).toBe( + `gccl/${SDK_VERSION} client/mcp`, + ); + expect(buildClientSurfaceHeader("cli")).toBe( + `gccl/${SDK_VERSION} client/cli`, + ); + }); +}); + +describe("mergeHeadersCaseInsensitive", () => { + it("replaces mixed-case duplicates without retaining earlier keys", () => { + const merged = mergeHeadersCaseInsensitive( + { + Accept: "application/json", + "X-Goog-Api-Client": "gccl/0.4.0 client/sdk", + }, + { + "x-goog-api-client": "gl-node/22.0.0 gccl/0.12.0 client/cli", + "X-Custom": "1", + }, + ); + + expect(merged).toEqual({ + Accept: "application/json", + "x-goog-api-client": "gl-node/22.0.0 gccl/0.12.0 client/cli", + "X-Custom": "1", + }); + expect(Object.keys(merged)).not.toContain("X-Goog-Api-Client"); + }); + + it("returns base headers cleanly when overrides are omitted", () => { + expect(mergeHeadersCaseInsensitive({ Accept: "application/json" })).toEqual( + { Accept: "application/json" }, + ); + }); +}); diff --git a/packages/sdk/test/unit/client.test.ts b/packages/sdk/test/unit/client.test.ts index f01bd42f..b81eb57a 100644 --- a/packages/sdk/test/unit/client.test.ts +++ b/packages/sdk/test/unit/client.test.ts @@ -18,6 +18,7 @@ import { StitchToolClient, __resetStitchHostWarning, } from "../../src/client.js"; +import { SDK_VERSION } from "../../src/version.js"; import { ZodError } from "zod"; // Mock child_process for gcloud calls @@ -128,6 +129,45 @@ describe("StitchToolClient", () => { const headers = client["buildAuthHeaders"](); expect(headers["Accept"]).toContain("application/json"); }); + + it("should emit X-Goog-Api-Client sdk surface header by default", () => { + const client = new StitchToolClient({ apiKey: "k" }); + const headers = client["buildAuthHeaders"](); + expect(headers["X-Goog-Api-Client"]).toBe( + `gccl/${SDK_VERSION} client/sdk`, + ); + }); + + it("should allow case-insensitive override of X-Goog-Api-Client via config.headers", () => { + const client = new StitchToolClient({ + apiKey: "k", + headers: { + "x-goog-api-client": "gl-node/22.0.0 gccl/0.12.0 client/cli", + }, + }); + const headers = client["buildAuthHeaders"](); + expect(headers["x-goog-api-client"]).toBe( + "gl-node/22.0.0 gccl/0.12.0 client/cli", + ); + expect(headers["X-Goog-Api-Client"]).toBeUndefined(); + expect(headers["X-Goog-Api-Key"]).toBe("k"); + }); + + it("should support spread-override of buildAuthHeaders by downstream wrappers", () => { + const client = new StitchToolClient({ apiKey: "k" }); + const headers = { + ...client["buildAuthHeaders"](), + "X-Goog-Api-Client": "gl-node/22.0.0 gccl/0.12.0 client/cli", + }; + expect(headers["X-Goog-Api-Client"]).toBe( + "gl-node/22.0.0 gccl/0.12.0 client/cli", + ); + expect( + Object.keys(headers).filter( + (k) => k.toLowerCase() === "x-goog-api-client", + ), + ).toEqual(["X-Goog-Api-Client"]); + }); }); // ─── Cycle 3: callTool response parsing ───────────────────────── @@ -506,6 +546,10 @@ describe("StitchToolClient", () => { requests: [], }); expect(capturedHeaders["X-Goog-Api-Key"]).toBe("test-key"); + expect(capturedHeaders["X-Goog-Api-Client"]).toBe( + `gccl/${SDK_VERSION} client/sdk`, + ); + expect(capturedHeaders["Content-Type"]).toBe("application/json"); }); // Test 11: throws StitchError with AUTH_FAILED on 401 diff --git a/packages/sdk/test/unit/proxy.test.ts b/packages/sdk/test/unit/proxy.test.ts index 7edb81d9..923857d4 100644 --- a/packages/sdk/test/unit/proxy.test.ts +++ b/packages/sdk/test/unit/proxy.test.ts @@ -15,8 +15,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { registerListToolsHandler } from "../../src/proxy/handlers/listTools.js"; import { registerCallToolHandler } from "../../src/proxy/handlers/callTool.js"; +import { StitchProxy } from "../../src/proxy/core.js"; import { downloadAssetsTool } from "../../src/proxy/virtual-tools.js"; import { EntityManager } from "../../src/entity-manager.js"; +import { SDK_VERSION } from "../../src/version.js"; import { ListToolsRequestSchema, CallToolRequestSchema, @@ -164,3 +166,32 @@ describe("Proxy Handlers", () => { ); }); }); + +describe("StitchProxy client surface header", () => { + it("tags upstream StitchToolClient requests as client/mcp by default", async () => { + const proxy = new StitchProxy({ apiKey: "proxy-key" }); + const upstreamClient = (proxy as any).ctx.client; + const headers = upstreamClient["buildAuthHeaders"](); + + expect(headers["X-Goog-Api-Key"]).toBe("proxy-key"); + expect(headers["X-Goog-Api-Client"]).toBe(`gccl/${SDK_VERSION} client/mcp`); + await proxy.close(); + }); + + it("allows custom headers to override X-Goog-Api-Client case-insensitively", async () => { + const proxy = new StitchProxy({ + apiKey: "proxy-key", + headers: { + "x-goog-api-client": "custom-mcp/1.0 client/mcp", + "X-Proxy-Trace": "trace-1", + }, + }); + const upstreamClient = (proxy as any).ctx.client; + const headers = upstreamClient["buildAuthHeaders"](); + + expect(headers["x-goog-api-client"]).toBe("custom-mcp/1.0 client/mcp"); + expect(headers["X-Goog-Api-Client"]).toBeUndefined(); + expect(headers["X-Proxy-Trace"]).toBe("trace-1"); + await proxy.close(); + }); +}); diff --git a/packages/sdk/test/unit/singleton.test.ts b/packages/sdk/test/unit/singleton.test.ts index 83a87a1d..d8880390 100644 --- a/packages/sdk/test/unit/singleton.test.ts +++ b/packages/sdk/test/unit/singleton.test.ts @@ -100,6 +100,24 @@ describe("getOrCreateClient", () => { expect(client2).not.toBe(client1); }); + it("invalidates the cache when headers change and reuses when key order differs", () => { + const client1 = getOrCreateClient({ + apiKey: "k", + headers: { "X-B": "2", "X-A": "1" }, + }); + const client2 = getOrCreateClient({ + apiKey: "k", + headers: { "X-A": "1", "X-B": "2" }, + }); + expect(client2).toBe(client1); + + const client3 = getOrCreateClient({ + apiKey: "k", + headers: { "X-Goog-Api-Client": "gccl/0.4.0 client/cli" }, + }); + expect(client3).not.toBe(client1); + }); + it("picks up STITCH_PROJECT_ID before GOOGLE_CLOUD_PROJECT", () => { vi.stubEnv("STITCH_ACCESS_TOKEN", "tok"); vi.stubEnv("STITCH_PROJECT_ID", "stitch-proj");