Skip to content
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
10 changes: 10 additions & 0 deletions docs/resources/developer.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ You can use the `CONTEXT7_API_KEY` environment variable instead of passing the `
- Integration with MCP server setups that use dotenv
- Tools that prefer environment variable configuration

### HTTP Transport CORS (Optional)

When running with `--transport http`, you can optionally restrict browser origins by setting:

```bash
CONTEXT7_ALLOWED_ORIGINS="https://chatgpt.com,https://chat.openai.com"
```

If `CONTEXT7_ALLOWED_ORIGINS` is not set, CORS remains permissive for compatibility.

<Warning>
The `--api-key` CLI flag takes precedence over the environment variable when both are provided.
</Warning>
Expand Down
32 changes: 30 additions & 2 deletions packages/mcp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,10 +273,34 @@ async function main() {
const initialPort = CLI_PORT ?? DEFAULT_PORT;

const app = express();
app.use(express.json());
app.use(express.json({ limit: "1mb" }));

// Optional CORS allowlist for browser clients. If not set, keep permissive CORS for compatibility.
const allowedOrigins = (() => {
const raw = process.env.CONTEXT7_ALLOWED_ORIGINS || process.env.ALLOWED_ORIGINS || "";
const parts = raw
.split(",")
.map((s) => s.trim())
.filter(Boolean);
return parts.length ? new Set(parts) : null;
})();

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
res.setHeader("Access-Control-Allow-Origin", "*");
const origin = String(req.headers.origin ?? "");

if (allowedOrigins) {
if (origin) {
if (!allowedOrigins.has(origin)) {
res.status(403).send("Origin not allowed");
return;
}
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
}
} else {
res.setHeader("Access-Control-Allow-Origin", "*");
}

res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");
res.setHeader(
"Access-Control-Allow-Headers",
Expand All @@ -285,6 +309,10 @@ async function main() {
res.setHeader("Access-Control-Expose-Headers", "MCP-Session-Id");

if (req.method === "OPTIONS") {
if (allowedOrigins && origin && !allowedOrigins.has(origin)) {
res.status(403).send("Origin not allowed");
return;
}
res.sendStatus(200);
return;
}
Expand Down