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
26 changes: 22 additions & 4 deletions src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> };
const url = resolveEnvPlaceholders(httpConfig.url);
const requestInit: RequestInit = {};
if (httpConfig.headers) {
const resolvedHeaders: Record<string, string> = {};
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<string, string> };
const url = resolveEnvPlaceholders(sseConfig.url);
const requestInit: RequestInit = {};
if (sseConfig.headers) {
const resolvedHeaders: Record<string, string> = {};
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)');
}
Expand Down
272 changes: 272 additions & 0 deletions src/tests/unit/client-headers.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
2 changes: 2 additions & 0 deletions src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading