Repository navigation
Expand file tree
/
Copy pathbasic-auth-server.ts
More file actions
179 lines (153 loc) · 4.87 KB
/
Copy pathbasic-auth-server.ts
File metadata and controls
179 lines (153 loc) · 4.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/**
* Basic Auth Server Example
*
* Demonstrates how to create an MCP server with API key and JWT authentication
* using @mcp-toolkit/auth.
*
* Usage:
* npx tsx examples/basic-auth-server.ts
*
* Environment variables:
* MCP_API_KEY - A valid API key for authenticating requests
* JWT_SECRET - Secret for verifying JWT tokens
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { withAuth } from "@mcp-toolkit/auth";
import { createLogger } from "@mcp-toolkit/logger";
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
const API_KEYS = [
process.env["MCP_API_KEY"] ?? "dev-api-key-12345",
];
const JWT_SECRET = process.env["JWT_SECRET"] ?? "super-secret-jwt-key";
// ---------------------------------------------------------------------------
// Logger
// ---------------------------------------------------------------------------
const logger = createLogger({
level: "info",
format: "json",
defaultMeta: { service: "basic-auth-server" },
});
// ---------------------------------------------------------------------------
// Server setup -- API Key authentication
// ---------------------------------------------------------------------------
async function startApiKeyServer(): Promise<void> {
const server = new McpServer({
name: "basic-auth-api-key",
version: "1.0.0",
});
// Apply API key authentication
withAuth(server, {
type: "api-key",
keys: API_KEYS,
header: "x-api-key",
});
// Register a simple tool. Tool params are a Zod *raw shape* -- a plain object
// whose values are Zod schemas -- not JSON Schema.
server.tool(
"greet",
"Greet a user by name",
{
name: z.string().describe("The name to greet"),
},
async ({ name }) => {
logger.info("Greeting user", { name });
return {
content: [
{
type: "text" as const,
text: `Hello, ${name}! You have been successfully authenticated.`,
},
],
};
},
);
// Register a tool that accesses auth context
server.tool(
"whoami",
"Return information about the authenticated caller",
{},
async (_params, extra) => {
// `withAuth` attaches the AuthContext at `extra.auth`. That key is not
// part of the SDK's own extra type, so read it through a cast.
const auth = (extra as unknown as Record<string, unknown>)["auth"] as
| { authenticated: boolean; payload?: Record<string, unknown> }
| undefined;
return {
content: [
{
type: "text" as const,
text: JSON.stringify(
{
authenticated: auth?.authenticated ?? false,
payload: auth?.payload ?? null,
},
null,
2,
),
},
],
};
},
);
logger.info("Starting API Key auth server...");
const transport = new StdioServerTransport();
await server.connect(transport);
}
// ---------------------------------------------------------------------------
// Server setup -- JWT authentication
// ---------------------------------------------------------------------------
async function startJwtServer(): Promise<void> {
const server = new McpServer({
name: "basic-auth-jwt",
version: "1.0.0",
});
// Apply JWT authentication
withAuth(server, {
type: "jwt",
secret: JWT_SECRET,
algorithms: ["HS256"],
clockTolerance: 5,
});
// Register tools
server.tool(
"get-secret-data",
"Retrieve secret data (requires JWT auth)",
{
category: z.string().describe("Data category to fetch"),
},
async ({ category }) => {
logger.info("Fetching secret data", { category });
const secrets: Record<string, string> = {
finance: "Q4 revenue: $1.2M",
engineering: "Next release: v2.0 on March 15",
hr: "Team size: 42 engineers",
};
const data = secrets[category] ?? "No data found for that category";
return {
content: [{ type: "text" as const, text: data }],
};
},
);
logger.info("Starting JWT auth server...");
const transport = new StdioServerTransport();
await server.connect(transport);
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
const mode = process.argv[2] ?? "api-key";
if (mode === "jwt") {
startJwtServer().catch((err) => {
logger.error("Failed to start JWT server", err as Error);
process.exit(1);
});
} else {
startApiKeyServer().catch((err) => {
logger.error("Failed to start API Key server", err as Error);
process.exit(1);
});
}