Skip to content

feat: allow securing SSE transport with secret #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ The Playwright MCP server supports the following command-line options:
- `--user-data-dir <path>`: Path to the user data directory
- `--port <port>`: Port to listen on for SSE transport
- `--host <host>`: Host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
- `--secret`: Secret used to secure the SSE transport.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Users are bad at managing secrets. I think we should generate endpoint based on crypto-secure guid by default. And allow user to override it with full --endpoint. So they'll say npx @playwright/mcp --server http://localhost:0/my-secret for manual control, wdyt? We'll add path to certs later for tls.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should generate endpoint based on crypto-secure guid by default.

Absolutely, but let's do that in a follow-up.

allow user to override it with full --endpoint

Full endpoint control will bring us trouble down the road when adopting MCP OAuth, which has some well-known paths. --secret is enough to solve the problem at hand.

We'll add path to certs later for tls.

I don't think TLS is our business, would prefer the user to setup a reverse proxy for this. Imagine we implement TLS, and the next thing people ask for is automated Let's Encrypt provisioning.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case we can just wait - we can't expect users to opt into the --secret.

- `--allowed-origins <origins>`: Semicolon-separated list of origins to allow the browser to request. Default is to allow all. Origins matching both `--allowed-origins` and `--blocked-origins` will be blocked.
- `--blocked-origins <origins>`: Semicolon-separated list of origins to block the browser to request. Origins matching both `--allowed-origins` and `--blocked-origins` will be blocked.
- `--vision`: Run server that uses screenshots (Aria snapshots are used by default)
Expand Down
5 changes: 5 additions & 0 deletions config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ export type Config = {
*/
vision?: boolean;

/**
* Secret used to secure the SSE transport.
*/
secret?: string;

/**
* The directory to save output files.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type CLIOptions = {
blockedOrigins?: string[];
outputDir?: string;
noImageResponses?: boolean;
secret?: string;
};

const defaultConfig: Config = {
Expand Down Expand Up @@ -122,6 +123,7 @@ export async function configFromCLIOptions(cliOptions: CLIOptions): Promise<Conf
blockedOrigins: cliOptions.blockedOrigins,
},
outputDir: cliOptions.outputDir,
secret: cliOptions.secret,
};
}

Expand Down
1 change: 1 addition & 0 deletions src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ program
.option('--user-data-dir <path>', 'Path to the user data directory')
.option('--port <port>', 'Port to listen on for SSE transport.')
.option('--host <host>', 'Host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')
.option('--secret <secret>', 'Secret used to secure the SSE transport.')
.option('--allowed-origins <origins>', 'Semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)
.option('--blocked-origins <origins>', 'Semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', semicolonSeparatedList)
.option('--vision', 'Run server that uses screenshots (Aria snapshots are used by default)')
Expand Down
26 changes: 20 additions & 6 deletions src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ async function handleSSE(config: Config, req: http.IncomingMessage, res: http.Se

return await transport.handlePostMessage(req, res);
} else if (req.method === 'GET') {
const transport = new SSEServerTransport('/sse', res);
let url = '/sse';
if (config.secret)
url += '?' + new URLSearchParams({ secret: config.secret });

const transport = new SSEServerTransport(url, res);
sessions.set(transport.sessionId, transport);
const connection = await createConnection(config);
await connection.connect(transport);
Expand Down Expand Up @@ -109,6 +113,11 @@ export function startHttpTransport(config: Config, port: number, hostname: strin
const streamableSessions = new Map<string, StreamableHTTPServerTransport>();
const httpServer = http.createServer(async (req, res) => {
const url = new URL(`http://localhost${req.url}`);
if (config.secret && url.searchParams.get('secret') !== config.secret) {
res.statusCode = 403;
return res.end('Forbidden');
}

if (url.pathname.startsWith('/mcp'))
await handleStreamable(config, req, res, streamableSessions, connectionList);
else
Expand All @@ -117,23 +126,28 @@ export function startHttpTransport(config: Config, port: number, hostname: strin
httpServer.listen(port, hostname, () => {
const address = httpServer.address();
assert(address, 'Could not bind server socket');
let url: string;
let baseUrl: string;
if (typeof address === 'string') {
url = address;
baseUrl = address;
} else {
const resolvedPort = address.port;
let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
resolvedHost = 'localhost';
url = `http://${resolvedHost}:${resolvedPort}`;
baseUrl = `http://${resolvedHost}:${resolvedPort}`;
}

const sseUrl = new URL('/sse', baseUrl);
if (config.secret)
sseUrl.searchParams.set('secret', config.secret);

const message = [
`Listening on ${url}`,
`Listening on ${baseUrl}`,
'Put this in your client config:',
JSON.stringify({
'mcpServers': {
'playwright': {
'url': `${url}/sse`
'url': `${sseUrl}`
}
}
}, undefined, 2),
Expand Down
45 changes: 32 additions & 13 deletions tests/sse.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,31 @@ import { spawn } from 'node:child_process';
import path from 'node:path';
import { test as baseTest } from './fixtures.js';
import { expect } from 'playwright/test';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';

// NOTE: Can be removed when we drop Node.js 18 support and changed to import.meta.filename.
const __filename = url.fileURLToPath(import.meta.url);

const test = baseTest.extend<{ serverEndpoint: string }>({
const test = baseTest.extend<{ serverEndpoint: URL }>({
serverEndpoint: async ({}, use) => {
const cp = spawn('node', [path.join(path.dirname(__filename), '../cli.js'), '--port', '0'], { stdio: 'pipe' });
const cp = spawn('node', [path.join(path.dirname(__filename), '../cli.js'), '--port', '0', '--secret', 'mySecretValue'], { stdio: 'pipe' });
try {
let stdout = '';
const url = await new Promise<string>(resolve => cp.stdout?.on('data', data => {
const url = await new Promise<URL>(resolve => cp.stdout?.on('data', data => {
stdout += data.toString();
const match = stdout.match(/Listening on (http:\/\/.*)/);
if (match)
resolve(match[1]);
if (match) {
const baseURL = new URL(match[1]);
baseURL.searchParams.set('secret', 'mySecretValue');
resolve(baseURL);
}
}));

cp.stderr.pipe(process.stderr);
cp.stdout.pipe(process.stdout);

await use(url);
} finally {
cp.kill();
Expand All @@ -43,22 +52,32 @@ const test = baseTest.extend<{ serverEndpoint: string }>({
});

test('sse transport', async ({ serverEndpoint }) => {
// need dynamic import b/c of some ESM nonsense
const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js');
const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
const transport = new SSEClientTransport(new URL(serverEndpoint));
const transport = new SSEClientTransport(serverEndpoint);
const client = new Client({ name: 'test', version: '1.0.0' });
await client.connect(transport);
await client.ping();
});

test('sse transport auth', async ({ serverEndpoint }) => {
serverEndpoint.searchParams.delete('secret');
const transport = new SSEClientTransport(serverEndpoint);
const client = new Client({ name: 'test', version: '1.0.0' });
await expect(() => client.connect(transport)).rejects.toThrow(/403/);
});

test('streamable http transport', async ({ serverEndpoint }) => {
// need dynamic import b/c of some ESM nonsense
const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js');
const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
const transport = new StreamableHTTPClientTransport(new URL('/mcp', serverEndpoint));
serverEndpoint.pathname = '/mcp';
const transport = new StreamableHTTPClientTransport(serverEndpoint);
Comment on lines +62 to +70
Copy link
Preview

Copilot AI May 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Modifying the 'serverEndpoint' URL directly may cause unintended side-effects in subsequent tests if the same instance is shared; consider cloning the URL instance to isolate changes.

Copilot uses AI. Check for mistakes.

const client = new Client({ name: 'test', version: '1.0.0' });
await client.connect(transport);
await client.ping();
expect(transport.sessionId, 'has session support').toBeDefined();
});

test('streamable http transport auth', async ({ serverEndpoint }) => {
serverEndpoint.pathname = '/mcp';
serverEndpoint.searchParams.delete('secret');
const transport = new StreamableHTTPClientTransport(serverEndpoint);
const client = new Client({ name: 'test', version: '1.0.0' });
await expect(() => client.connect(transport)).rejects.toThrow(/403/);
});