Skip to content

Commit e6b02fb

Browse files
Theodor N. EngøyTheodor N. Engøy
authored andcommitted
examples: restrict default CORS to localhost
1 parent e1a6b71 commit e6b02fb

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

examples/server/src/ssePollingExample.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,29 @@ const HOST = process.env.MCP_HOST ?? 'localhost';
8787
const PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_PORT, 10) : 3001;
8888

8989
const app = createMcpExpressApp({ host: HOST });
90-
app.use(cors());
90+
const DEFAULT_CORS_ORIGIN_REGEX = /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/;
91+
92+
let corsOriginRegex = DEFAULT_CORS_ORIGIN_REGEX;
93+
if (process.env.MCP_CORS_ORIGIN_REGEX) {
94+
try {
95+
corsOriginRegex = new RegExp(process.env.MCP_CORS_ORIGIN_REGEX);
96+
} catch (error) {
97+
const msg =
98+
error && typeof error === 'object' && 'message' in error ? String((error as { message: unknown }).message) : String(error);
99+
console.warn(`Invalid MCP_CORS_ORIGIN_REGEX (${process.env.MCP_CORS_ORIGIN_REGEX}): ${msg}`);
100+
corsOriginRegex = DEFAULT_CORS_ORIGIN_REGEX;
101+
}
102+
}
103+
104+
app.use(
105+
cors({
106+
origin: (origin, cb) => {
107+
// Allow non-browser clients (no Origin header).
108+
if (!origin) return cb(null, true);
109+
return cb(null, corsOriginRegex.test(origin));
110+
}
111+
})
112+
);
91113

92114
// Create event store for resumability
93115
const eventStore = new InMemoryEventStore();

0 commit comments

Comments
 (0)