Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
9 changes: 9 additions & 0 deletions .changeset/quiet-mcp-guards.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@voltagent/server-core": patch
---

fix(server-core): require authentication for MCP execution routes under legacy `auth`

The legacy auth policy protected agent, tool, and workflow execution but left the MCP execution routes open, so an MCP client could call exposed tools, agents, and workflows without a token. `PROTECTED_ROUTES` now includes the MCP Streamable HTTP route (`/mcp/:serverId/mcp`), the SSE connection and message routes (`GET /mcp/:serverId/sse`, `POST /mcp/:serverId/messages`), MCP tool invocation, reading a single MCP prompt or resource, and the logging level route. MCP discovery is unchanged: `GET /mcp/servers`, `GET /mcp/servers/:serverId` and `GET /mcp/servers/:serverId/tools` stay public, and the prompt, resource and resource template lists stay public in the default mode (with `defaultPrivate: true` they require auth, as before). Apps that relied on unauthenticated MCP access can opt back in with `publicRoutes`. `requiresAuth()` also matches a path with a trailing slash and a `HEAD` request the same way as the route without the slash and its `GET`, so those spellings no longer reach protected handlers without a token.

Fixes #1493
77 changes: 77 additions & 0 deletions packages/server-core/src/auth/defaults.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,41 @@ describe("Auth Defaults", () => {
expect(requiresAuth("POST", "/workflows/test/executions/exec-789/cancel")).toBe(true);
});

it("should require auth for MCP transport endpoints", () => {
expect(requiresAuth("POST", "/mcp/my-server/mcp")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/mcp")).toBe(true);
expect(requiresAuth("DELETE", "/mcp/my-server/mcp")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/sse")).toBe(true);
expect(requiresAuth("POST", "/mcp/my-server/messages")).toBe(true);
});

it("should require auth for MCP tool invocation and logging control", () => {
expect(requiresAuth("POST", "/mcp/servers/my-server/tools/search")).toBe(true);
expect(requiresAuth("POST", "/mcp/my-server/tools/search/invoke")).toBe(true);
expect(requiresAuth("POST", "/mcp/servers/my-server/logging/level")).toBe(true);
expect(requiresAuth("POST", "/mcp/my-server/logging/level")).toBe(true);
});

it("should require auth for reading MCP prompts and resources", () => {
expect(requiresAuth("GET", "/mcp/servers/my-server/prompts/greet")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/prompts/greet")).toBe(true);
expect(requiresAuth("GET", "/mcp/servers/my-server/resources/contents")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/resources/read")).toBe(true);
});

it("should keep MCP prompt and resource listings public", () => {
expect(requiresAuth("GET", "/mcp/servers/my-server/prompts")).toBe(false);
expect(requiresAuth("GET", "/mcp/servers/my-server/resources")).toBe(false);
expect(requiresAuth("GET", "/mcp/servers/my-server/resource-templates")).toBe(false);
});

it("should keep MCP discovery public while protecting MCP execution", () => {
expect(requiresAuth("GET", "/mcp/servers")).toBe(false);
expect(requiresAuth("GET", "/mcp/servers/my-server")).toBe(false);
expect(requiresAuth("GET", "/mcp/servers/my-server/tools")).toBe(false);
expect(requiresAuth("POST", "/mcp/my-server/mcp")).toBe(true);
});

it("should require auth for all observability endpoints via wildcard", () => {
expect(requiresAuth("GET", "/observability/traces")).toBe(true);
expect(requiresAuth("GET", "/observability/spans/abc-123")).toBe(true);
Expand Down Expand Up @@ -193,6 +228,13 @@ describe("Auth Defaults", () => {

expect(requiresAuth("POST", "/agents/test/text", publicRoutes)).toBe(false);
});

it("should allow making MCP transport routes public via publicRoutes", () => {
const publicRoutes = ["/mcp/:serverId/mcp"];

expect(requiresAuth("POST", "/mcp/my-server/mcp", publicRoutes)).toBe(false);
expect(requiresAuth("POST", "/mcp/my-server/messages", publicRoutes)).toBe(true);
});
});
});

Expand All @@ -219,6 +261,22 @@ describe("Auth Defaults", () => {
});
});

describe("MCP Routes (Opt-Out Mode)", () => {
it("should keep MCP discovery public and protect MCP execution with defaultPrivate", () => {
expect(requiresAuth("GET", "/mcp/servers", undefined, true)).toBe(false);
expect(requiresAuth("GET", "/mcp/servers/my-server/tools", undefined, true)).toBe(false);
expect(requiresAuth("POST", "/mcp/my-server/mcp", undefined, true)).toBe(true);
});

it("should require auth for MCP prompt and resource lists with defaultPrivate", () => {
expect(requiresAuth("GET", "/mcp/servers/my-server/prompts", undefined, true)).toBe(true);
expect(requiresAuth("GET", "/mcp/servers/my-server/resources", undefined, true)).toBe(true);
expect(
requiresAuth("GET", "/mcp/servers/my-server/resource-templates", undefined, true),
).toBe(true);
});
});

describe("Custom Routes (Opt-Out Mode) - Main Feature", () => {
it("should require auth for custom routes when defaultPrivate is true", () => {
// This is the NEW behavior - custom routes are protected by default
Expand Down Expand Up @@ -364,6 +422,25 @@ describe("Auth Defaults", () => {
expect(requiresAuth("POST", "/webhooks/stripe-test", publicRoutes)).toBe(false);
expect(requiresAuth("GET", "/api/data-export", publicRoutes)).toBe(false);
});

it("should match trailing-slash paths like the route without the slash", () => {
expect(requiresAuth("POST", "/mcp/my-server/tools/search/invoke/")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/resources/read/")).toBe(true);
expect(requiresAuth("GET", "/mcp/my-server/prompts/greet/")).toBe(true);
expect(requiresAuth("POST", "/agents/test/text/")).toBe(true);
expect(requiresAuth("GET", "/mcp/servers/")).toBe(false);
expect(requiresAuth("GET", "/")).toBe(false);
expect(requiresAuth("GET", "/api/custom/", ["GET /api/custom"], true)).toBe(false);
});

it("should treat HEAD like GET", () => {
expect(requiresAuth("HEAD", "/mcp/servers/my-server/prompts/greet")).toBe(true);
expect(requiresAuth("HEAD", "/mcp/my-server/resources/read")).toBe(true);
expect(requiresAuth("HEAD", "/mcp/my-server/sse")).toBe(true);
expect(requiresAuth("head", "/mcp/my-server/sse")).toBe(true);
expect(requiresAuth("HEAD", "/mcp/servers")).toBe(false);
expect(requiresAuth("HEAD", "/api/data", ["GET /api/data"], true)).toBe(false);
});
});

describe("Constants Validation", () => {
Expand Down
35 changes: 29 additions & 6 deletions packages/server-core/src/auth/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,23 @@ export const PROTECTED_ROUTES = [
"POST /workflows/:id/executions/:executionId/replay", // Replay execution from historical step
"POST /workflows/:id/executions/:executionId/cancel", // Cancel execution

// ========================================
// MCP EXECUTION (Tools, Agents, Workflows, Prompts, Resources)
// Not listed here: discovery. Server list/details and tool lists are in DEFAULT_LEGACY_PUBLIC_ROUTES;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: Elysia's MCP discovery routes are not in DEFAULT_LEGACY_PUBLIC_ROUTES, so defaultPrivate: true now leaves GET /mcp, GET /mcp/:serverId, and GET /mcp/:serverId/tools protected. Add the Elysia discovery patterns to the legacy public list, or qualify the policy and documentation to make this framework difference explicit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/server-core/src/auth/defaults.ts, line 127:

<comment>Elysia's MCP discovery routes are not in `DEFAULT_LEGACY_PUBLIC_ROUTES`, so `defaultPrivate: true` now leaves `GET /mcp`, `GET /mcp/:serverId`, and `GET /mcp/:serverId/tools` protected. Add the Elysia discovery patterns to the legacy public list, or qualify the policy and documentation to make this framework difference explicit.</comment>

<file context>
@@ -122,6 +122,23 @@ export const PROTECTED_ROUTES = [
 
+  // ========================================
+  // MCP EXECUTION (Tools, Agents, Workflows, Prompts, Resources)
+  // Not listed here: discovery. Server list/details and tool lists are in DEFAULT_LEGACY_PUBLIC_ROUTES;
+  // prompt, resource and resource template lists stay public unless defaultPrivate is true
+  // ========================================
</file context>

// prompt, resource and resource template lists stay public unless defaultPrivate is true
// ========================================
"/mcp/:serverId/mcp", // Streamable HTTP transport (GET/POST/DELETE)
"GET /mcp/:serverId/sse", // SSE transport connection
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
"POST /mcp/:serverId/messages", // SSE transport messages
"POST /mcp/servers/:serverId/tools/:toolName", // Invoke MCP tool (Hono)
"POST /mcp/:serverId/tools/:toolName/invoke", // Invoke MCP tool (Elysia)
"POST /mcp/servers/:serverId/logging/level", // Set MCP logging level (Hono)
"POST /mcp/:serverId/logging/level", // Set MCP logging level (Elysia)
"GET /mcp/servers/:serverId/prompts/:promptName", // Get MCP prompt (Hono)
"GET /mcp/:serverId/prompts/:promptName", // Get MCP prompt (Elysia)
"GET /mcp/servers/:serverId/resources/contents", // Read MCP resource (Hono)
"GET /mcp/:serverId/resources/read", // Read MCP resource (Elysia)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

// ========================================
// MEMORY (User Data)
// ========================================
Expand Down Expand Up @@ -232,17 +249,23 @@ export function requiresAuth(
publicRoutes?: string[],
defaultPrivate?: boolean,
): boolean {
// HEAD is served by GET handlers, and a trailing slash can reach the same handler
// (Elysia's default non-strict routing), so match both against the canonical route
const upperMethod = method.toUpperCase();
const normalizedMethod = upperMethod === "HEAD" ? "GET" : upperMethod;
const normalizedPath = path.replace(/\/+$/, "") || "/";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Check if it's a default public route
for (const publicRoute of DEFAULT_LEGACY_PUBLIC_ROUTES) {
if (publicRoute.includes(" ")) {
// Route with method specified
const [routeMethod, routePath] = publicRoute.split(" ");
if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) {
if (normalizedMethod === routeMethod && pathMatches(normalizedPath, routePath)) {
return false; // Public route, no auth required
}
} else {
// Route without method (any method)
if (pathMatches(path, publicRoute)) {
if (pathMatches(normalizedPath, publicRoute)) {
return false; // Public route, no auth required
}
}
Expand All @@ -254,12 +277,12 @@ export function requiresAuth(
if (publicRoute.includes(" ")) {
// Route with method specified
const [routeMethod, routePath] = publicRoute.split(" ");
if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) {
if (normalizedMethod === routeMethod && pathMatches(normalizedPath, routePath)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return false; // Public route, no auth required
}
} else {
// Route without method (any method)
if (pathMatches(path, publicRoute)) {
if (pathMatches(normalizedPath, publicRoute)) {
return false; // Public route, no auth required
}
}
Expand All @@ -271,12 +294,12 @@ export function requiresAuth(
if (protectedRoute.includes(" ")) {
// Route with method specified
const [routeMethod, routePath] = protectedRoute.split(" ");
if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) {
if (normalizedMethod === routeMethod && pathMatches(normalizedPath, routePath)) {
return true; // Protected route, auth required
}
} else {
// Route without method (any method)
if (pathMatches(path, protectedRoute)) {
if (pathMatches(normalizedPath, protectedRoute)) {
return true; // Protected route, auth required
}
}
Expand Down
87 changes: 87 additions & 0 deletions packages/server-elysia/src/auth/middleware.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,93 @@ describe("Auth Middleware - conversationId & Options Preservation", () => {
expect(json.error).toBe("Authentication required");
});

it("should return 401 for MCP prompt and resource reads when token is missing", async () => {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const app = new Elysia()
.state("authenticatedUser", null as any)
.onBeforeHandle(createAuthMiddleware(mockAuthProvider))
.get("/mcp/:serverId/prompts/:promptName", () => ({ success: true }))
.get("/mcp/:serverId/resources/read", () => ({ success: true }));

for (const path of ["/mcp/test-server/prompts/greet", "/mcp/test-server/resources/read"]) {
const res = await app.handle(new Request(`http://localhost:3000${path}`));

expect(res.status).toBe(401);
const json = await res.json();
expect(json.error).toBe("Authentication required");
}
});

it("should return 401 for MCP tool invocation when token is missing", async () => {
const app = new Elysia()
.state("authenticatedUser", null as any)
.onBeforeHandle(createAuthMiddleware(mockAuthProvider))
.post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true }))
.post("/mcp/:serverId/logging/level", () => ({ success: true }));

for (const path of [
"/mcp/test-server/tools/search/invoke",
"/mcp/test-server/logging/level",
]) {
const res = await app.handle(
new Request(`http://localhost:3000${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
}),
);

expect(res.status).toBe(401);
const json = await res.json();
expect(json.error).toBe("Authentication required");
}
});

it("should return 401 for trailing-slash MCP tool invocation when token is missing", async () => {
const app = new Elysia()
.state("authenticatedUser", null as any)
.onBeforeHandle(createAuthMiddleware(mockAuthProvider))
.post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true }));

const res = await app.handle(
new Request("http://localhost:3000/mcp/test-server/tools/search/invoke/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
}),
);

expect(res.status).toBe(401);
});

it("should let authenticated requests reach MCP tool invocation", async () => {
const app = new Elysia()
.state("authenticatedUser", null as any)
.onBeforeHandle(createAuthMiddleware(mockAuthProvider))
.post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true }));

for (const path of [
"/mcp/test-server/tools/search/invoke",
"/mcp/test-server/tools/search/invoke/",
]) {
const res = await app.handle(
new Request(`http://localhost:3000${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer valid-token",
},
body: JSON.stringify({}),
}),
);

expect(res.status).toBe(200);
const json = await res.json();
expect(json.success).toBe(true);
}
});

it("should return 401 when token is invalid", async () => {
mockAuthProvider.defaultPrivate = true;

Expand Down
32 changes: 32 additions & 0 deletions packages/server-hono/src/auth/middleware.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,38 @@ describe("Auth Middleware - conversationId & Options Preservation", () => {
expect(json.error).toBe("Authentication required");
});

it("should return 401 for MCP execution routes when token is missing", async () => {
const middleware = createAuthMiddleware(mockAuthProvider);
const routes: Array<[string, string]> = [
["/mcp/test-server/mcp", "POST"],
["/mcp/test-server/sse", "GET"],
["/mcp/test-server/messages", "POST"],
["/mcp/servers/test-server/tools/search", "POST"],
["/mcp/servers/test-server/logging/level", "POST"],
["/mcp/servers/test-server/prompts/greet", "GET"],
["/mcp/servers/test-server/resources/contents", "GET"],
];

for (const [path, method] of routes) {
mockContext = createMockContext(path, method, {});
const response = await middleware(mockContext as Context, mockNext);

expect(response?.status).toBe(401);
}

expect(mockNext).not.toHaveBeenCalled();
});

it("should let authenticated requests reach MCP execution routes", async () => {
mockContext = createMockContext("/mcp/test-server/mcp", "POST", {}, "valid-token");

const middleware = createAuthMiddleware(mockAuthProvider);
await middleware(mockContext as Context, mockNext);

expect(mockAuthProvider.verifyToken).toHaveBeenCalled();
expect(mockNext).toHaveBeenCalled();
});

it("should return 401 when token is invalid", async () => {
mockContext = createMockContext(
"/agents/test-agent/text",
Expand Down
3 changes: 2 additions & 1 deletion website/docs/api/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ if (process.env.NODE_ENV === "production") {
Legacy auth uses two default lists:

- **DEFAULT_LEGACY_PUBLIC_ROUTES** (alias `DEFAULT_PUBLIC_ROUTES`): management, docs, discovery
- **PROTECTED_ROUTES**: execution, tool execution, observability, updates
- **PROTECTED_ROUTES**: execution, tool execution, MCP execution (transports, tool invocation, prompt and resource reads, logging level), observability, updates

When `auth` is enabled:

Expand All @@ -626,6 +626,7 @@ If you need `/agents`, `/workflows`, `/doc`, or `/ui` protected, use **authNext*
| Endpoint Type | Legacy Auth (Default) | Legacy Auth (defaultPrivate: true) |
| --------------------------------- | --------------------- | ---------------------------------- |
| Execution (`POST /agents/*/text`) | Protected | Protected |
| MCP execution (`/mcp/*/mcp`) | Protected | Protected |
| Management (`GET /agents`) | Public | Public |
| Docs (`/doc`, `/ui`) | Public | Public |
| Custom routes | Public | Protected |
Expand Down