From 498cd3db7117154025fe49ae68674df2dc01d4d1 Mon Sep 17 00:00:00 2001 From: mutallipp Date: Tue, 28 Apr 2026 10:33:11 +0800 Subject: [PATCH 1/2] feat: support custom headers for HTTP/SSE transports Pass headers from server config to StreamableHTTPClientTransport and SSEClientTransport via requestInit. This enables authentication for HTTP-based MCP servers (e.g. Arthas MCP) that require Authorization or other custom headers. Changes: - config.ts: add optional 'type' and 'headers' fields to HttpServerConfigSchema - client.ts: read config.headers and pass as requestInit.headers to transports - Environment variable placeholders in header values are resolved --- src/core/client.ts | 26 ++++++++++++++++++++++---- src/types/config.ts | 2 ++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/core/client.ts b/src/core/client.ts index 99137e4..da14516 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -103,11 +103,29 @@ export class McpClientService { env: env, }); } else if (serverType === 'http' && 'url' in config) { - const url = resolveEnvPlaceholders((config as { url: string }).url); - this.transport = new StreamableHTTPClientTransport(new URL(url)); + const httpConfig = config as { url: string; headers?: Record }; + const url = resolveEnvPlaceholders(httpConfig.url); + const requestInit: RequestInit = {}; + if (httpConfig.headers) { + const resolvedHeaders: Record = {}; + for (const key in httpConfig.headers) { + resolvedHeaders[key] = resolveEnvPlaceholders(httpConfig.headers[key]); + } + requestInit.headers = resolvedHeaders; + } + this.transport = new StreamableHTTPClientTransport(new URL(url), { requestInit }); } else if ('url' in config) { - const url = resolveEnvPlaceholders((config as { url: string }).url); - this.transport = new SSEClientTransport(new URL(url)); + const sseConfig = config as { url: string; headers?: Record }; + const url = resolveEnvPlaceholders(sseConfig.url); + const requestInit: RequestInit = {}; + if (sseConfig.headers) { + const resolvedHeaders: Record = {}; + for (const key in sseConfig.headers) { + resolvedHeaders[key] = resolveEnvPlaceholders(sseConfig.headers[key]); + } + requestInit.headers = resolvedHeaders; + } + this.transport = new SSEClientTransport(new URL(url), { requestInit }); } else { throw new Error('Invalid server configuration: must have either command (for stdio) or url (for sse/http)'); } diff --git a/src/types/config.ts b/src/types/config.ts index 846345c..3934842 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -13,6 +13,8 @@ export const StdioServerConfigSchema = z.object({ // Standard MCP server configuration (sse/http type) export const HttpServerConfigSchema = z.object({ url: z.string().url(), + type: z.enum(['sse', 'streamableHttp', 'http']).optional(), + headers: z.record(z.string()).optional(), disabled: z.boolean().optional(), autoApprove: z.array(z.string()).optional(), }).passthrough(); From b5a37bf44355459dbafd0f5c38b4e8b7c7dcb29f Mon Sep 17 00:00:00 2001 From: mutallipp Date: Tue, 28 Apr 2026 10:45:34 +0800 Subject: [PATCH 2/2] test: add unit tests for HTTP/SSE headers support - detectServerType: http, sse, stdio detection - StreamableHTTP: headers passed, no headers, env placeholder resolution, missing env error - SSE: headers passed, no headers, env placeholder resolution - HttpServerConfigSchema: headers/type validation, reject invalid type/non-string headers 17 new tests, all 62 tests passing. --- src/tests/unit/client-headers.test.ts | 272 ++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 src/tests/unit/client-headers.test.ts diff --git a/src/tests/unit/client-headers.test.ts b/src/tests/unit/client-headers.test.ts new file mode 100644 index 0000000..b6f470b --- /dev/null +++ b/src/tests/unit/client-headers.test.ts @@ -0,0 +1,272 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// Mock the MCP SDK transports before importing client +const mockStreamableHTTPConnect = vi.fn().mockResolvedValue(undefined); +const mockSSEConnect = vi.fn().mockResolvedValue(undefined); + +let capturedStreamableHTTPUrl: URL | undefined; +let capturedStreamableHTTPOpts: any; +let capturedSSEUrl: URL | undefined; +let capturedSSEOpts: any; + +vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({ + StreamableHTTPClientTransport: class { + constructor(url: URL, opts?: any) { + capturedStreamableHTTPUrl = url; + capturedStreamableHTTPOpts = opts; + } + start = mockStreamableHTTPConnect; + close = vi.fn(); + set onclose(_: any) {} + set onerror(_: any) {} + set onmessage(_: any) {} + } +})); + +vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({ + SSEClientTransport: class { + constructor(url: URL, opts?: any) { + capturedSSEUrl = url; + capturedSSEOpts = opts; + } + start = mockSSEConnect; + close = vi.fn(); + set onclose(_: any) {} + set onerror(_: any) {} + set onmessage(_: any) {} + } +})); + +vi.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({ + StdioClientTransport: class { + constructor(_opts: any) {} + start = vi.fn().mockResolvedValue(undefined); + close = vi.fn(); + set onclose(_: any) {} + set onerror(_: any) {} + set onmessage(_: any) {} + } +})); + +vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({ + Client: class { + constructor(_info: any, _opts: any) {} + connect = vi.fn().mockResolvedValue(undefined); + listTools = vi.fn().mockResolvedValue({ tools: [] }); + callTool = vi.fn().mockResolvedValue({ result: 'ok' }); + close = vi.fn(); + } +})); + +vi.mock('eventsource', () => ({ + EventSource: class {} +})); + +import { McpClientService } from '../../core/client.js'; +import { detectServerType, HttpServerConfigSchema } from '../../types/config.js'; + +describe('detectServerType', () => { + it('should detect http type for non-sse URLs', () => { + expect(detectServerType({ url: 'http://localhost:8563/mcp' })).toBe('http'); + }); + + it('should detect sse type for URLs ending with /sse', () => { + expect(detectServerType({ url: 'http://localhost:3000/sse' })).toBe('sse'); + }); + + it('should detect sse type for URLs containing /sse', () => { + expect(detectServerType({ url: 'http://localhost:3000/sse?token=abc' })).toBe('sse'); + }); + + it('should detect stdio type for command-based configs', () => { + expect(detectServerType({ command: 'node', args: ['server.js'] })).toBe('stdio'); + }); +}); + +describe('McpClientService - HTTP headers support', () => { + let service: McpClientService; + + beforeEach(() => { + service = new McpClientService(); + capturedStreamableHTTPUrl = undefined; + capturedStreamableHTTPOpts = undefined; + capturedSSEUrl = undefined; + capturedSSEOpts = undefined; + }); + + afterEach(() => { + service.close(); + }); + + describe('StreamableHTTP transport', () => { + it('should pass headers to StreamableHTTPClientTransport', async () => { + await service.connect({ + url: 'http://localhost:8563/mcp', + headers: { + 'Authorization': 'Bearer test-token-123', + 'X-Custom-Header': 'custom-value' + } + }, 'test-http'); + + expect(capturedStreamableHTTPUrl?.toString()).toBe('http://localhost:8563/mcp'); + expect(capturedStreamableHTTPOpts).toBeDefined(); + expect(capturedStreamableHTTPOpts.requestInit).toBeDefined(); + expect(capturedStreamableHTTPOpts.requestInit.headers).toEqual({ + 'Authorization': 'Bearer test-token-123', + 'X-Custom-Header': 'custom-value' + }); + }); + + it('should work without headers', async () => { + await service.connect({ + url: 'http://localhost:8563/mcp' + }, 'test-http-no-headers'); + + expect(capturedStreamableHTTPUrl?.toString()).toBe('http://localhost:8563/mcp'); + expect(capturedStreamableHTTPOpts).toBeDefined(); + // requestInit should exist but headers should be empty/undefined + expect(capturedStreamableHTTPOpts.requestInit.headers).toBeUndefined(); + }); + + it('should resolve env placeholders in header values', async () => { + process.env.TEST_TOKEN = 'resolved-token-value'; + + await service.connect({ + url: 'http://localhost:8563/mcp', + headers: { + 'Authorization': 'Bearer ${TEST_TOKEN}' + } + }, 'test-http-env'); + + expect(capturedStreamableHTTPOpts.requestInit.headers).toEqual({ + 'Authorization': 'Bearer resolved-token-value' + }); + + delete process.env.TEST_TOKEN; + }); + + it('should throw on missing env variable in headers', async () => { + delete process.env.NONEXISTENT_VAR; + + await expect(service.connect({ + url: 'http://localhost:8563/mcp', + headers: { + 'Authorization': 'Bearer ${NONEXISTENT_VAR}' + } + }, 'test-http-missing-env')).rejects.toThrow('Missing environment variables'); + }); + }); + + describe('SSE transport', () => { + it('should pass headers to SSEClientTransport', async () => { + await service.connect({ + url: 'http://localhost:3000/sse', + headers: { + 'Authorization': 'Bearer sse-token', + 'X-API-Key': 'api-key-123' + } + }, 'test-sse'); + + expect(capturedSSEUrl?.toString()).toBe('http://localhost:3000/sse'); + expect(capturedSSEOpts).toBeDefined(); + expect(capturedSSEOpts.requestInit).toBeDefined(); + expect(capturedSSEOpts.requestInit.headers).toEqual({ + 'Authorization': 'Bearer sse-token', + 'X-API-Key': 'api-key-123' + }); + }); + + it('should work without headers for SSE', async () => { + await service.connect({ + url: 'http://localhost:3000/sse' + }, 'test-sse-no-headers'); + + expect(capturedSSEUrl?.toString()).toBe('http://localhost:3000/sse'); + expect(capturedSSEOpts).toBeDefined(); + expect(capturedSSEOpts.requestInit.headers).toBeUndefined(); + }); + + it('should resolve env placeholders in SSE header values', async () => { + process.env.SSE_SECRET = 'my-sse-secret'; + + await service.connect({ + url: 'http://localhost:3000/sse', + headers: { + 'X-Secret': '${SSE_SECRET}' + } + }, 'test-sse-env'); + + expect(capturedSSEOpts.requestInit.headers).toEqual({ + 'X-Secret': 'my-sse-secret' + }); + + delete process.env.SSE_SECRET; + }); + }); +}); + +describe('HttpServerConfigSchema - headers validation', () => { + + it('should accept config with headers', () => { + const config = { + url: 'http://localhost:8563/mcp', + headers: { + 'Authorization': 'Bearer token123' + } + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(true); + }); + + it('should accept config without headers', () => { + const config = { + url: 'http://localhost:8563/mcp' + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(true); + }); + + it('should accept config with type field', () => { + const config = { + url: 'http://localhost:8563/mcp', + type: 'streamableHttp' + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(true); + }); + + it('should accept config with all optional fields', () => { + const config = { + url: 'http://localhost:8563/mcp', + type: 'http', + headers: { + 'Authorization': 'Bearer token', + 'X-Custom': 'value' + }, + disabled: false, + autoApprove: ['*'] + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(true); + }); + + it('should reject config with invalid type value', () => { + const config = { + url: 'http://localhost:8563/mcp', + type: 'invalid-type' + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(false); + }); + + it('should reject config with non-string header values', () => { + const config = { + url: 'http://localhost:8563/mcp', + headers: { + 'Authorization': 123 + } + }; + const result = HttpServerConfigSchema.safeParse(config); + expect(result.success).toBe(false); + }); +});