Skip to content
Merged
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
45 changes: 45 additions & 0 deletions packages/sdk/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,58 @@
* 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;
/** Google Cloud project ID for quota/billing with Bearer auth. */
quotaProjectId?: string;
}

/**
* Build the Google API client telemetry header identifying the Stitch SDK
* version and top-level client surface (`gccl/<version> client/<surface>`).
*/
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<string, string>,
overrides?: Record<string, string>,
): Record<string, string> {
const merged: Record<string, string> = {};
const keyByLower = new Map<string, string>();

const apply = (source: Record<string, string>) => {
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.
*
Expand Down
34 changes: 21 additions & 13 deletions packages/sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -87,6 +91,7 @@ export function resolveConfigWithEnv(
env("GOOGLE_CLOUD_PROJECT"),
baseUrl,
timeout: input?.timeout,
headers: input?.headers,
retry: input?.retry,
entityCache: input?.entityCache,
};
Expand Down Expand Up @@ -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<string, string> {
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<T>(result: any, name: string): T {
Expand Down Expand Up @@ -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),
});

Expand Down
9 changes: 9 additions & 0 deletions packages/sdk/src/proxy/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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[],
};
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/singleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface SingletonClientConfig {
projectId?: string;
baseUrl?: string;
timeout?: number;
headers?: Record<string, string>;
retry?: StitchConfig["retry"];
entityCache?: boolean;
}
Expand Down Expand Up @@ -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,
});
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/spec/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/spec/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
50 changes: 49 additions & 1 deletion packages/sdk/test/unit/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -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" },
);
});
});
44 changes: 44 additions & 0 deletions packages/sdk/test/unit/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ─────────────────────────
Expand Down Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions packages/sdk/test/unit/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
});
});
Loading
Loading