@smithery/sdk 1.6.7 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,12 +1,20 @@
1
1
  {
2
2
  "name": "@smithery/sdk",
3
- "version": "1.6.7",
3
+ "version": "1.7.0",
4
4
  "description": "SDK to develop with Smithery",
5
5
  "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/smithery-ai/sdk"
9
+ },
6
10
  "main": "./dist/index.js",
7
11
  "types": "./dist/index.d.ts",
8
12
  "exports": {
9
13
  ".": "./dist/index.js",
14
+ "./react": "./dist/react/index.js",
15
+ "./openai": "./dist/openai/index.js",
16
+ "./server": "./dist/server/index.js",
17
+ "./helpers": "./dist/helpers/index.js",
10
18
  "./*": "./dist/*"
11
19
  },
12
20
  "files": [
@@ -21,7 +29,8 @@
21
29
  "packageManager": "npm@11.4.1",
22
30
  "license": "MIT",
23
31
  "dependencies": {
24
- "@modelcontextprotocol/sdk": "^1.18.0",
32
+ "@modelcontextprotocol/sdk": "^1.18.1",
33
+ "chalk": "^5.6.2",
25
34
  "express": "^5.1.0",
26
35
  "jose": "^6.1.0",
27
36
  "json-schema": "^0.4.0",
@@ -37,6 +46,7 @@
37
46
  "@types/json-schema": "^7.0.15",
38
47
  "@types/lodash": "^4.17.17",
39
48
  "@types/node": "^20.0.0",
49
+ "@types/react": "^18.3.12",
40
50
  "@types/uuid": "^9.0.7",
41
51
  "dotenv": "^16.4.7",
42
52
  "tsx": "^4.19.2",
package/dist/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export * from "./shared/config.js";
2
- export * from "./shared/patch.js";
3
- export { createStatefulServer, type StatefulServerOptions, } from "./server/stateful.js";
4
- export * from "./server/session.js";
5
- export * from "./server/auth/identity.js";
6
- export * from "./server/auth/oauth.js";
package/dist/index.js DELETED
@@ -1,11 +0,0 @@
1
- // Smithery SDK – Barrel file
2
- // Central re-exports so that `dist/index.js` & `index.d.ts` are generated.
3
- // Update this list whenever a new top-level feature is added.
4
- // Shared utilities
5
- export * from "./shared/config.js";
6
- export * from "./shared/patch.js";
7
- // Server-side helpers (selective to avoid duplicate type names)
8
- export { createStatefulServer, } from "./server/stateful.js";
9
- export * from "./server/session.js";
10
- export * from "./server/auth/identity.js";
11
- export * from "./server/auth/oauth.js";
@@ -1,18 +0,0 @@
1
- import type { Application, Request, Router } from "express";
2
- import { type JWTPayload } from "jose";
3
- import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
4
- export type IdentityJwtClaims = JWTPayload & Record<string, unknown>;
5
- export interface IdentityHandler {
6
- /** Base path to mount metadata and token endpoints. Default: "/" */
7
- basePath?: string;
8
- /** Expected JWT issuer. Default: "https://server.smithery.ai" */
9
- issuer?: string;
10
- /** JWKS URL for issuer. Default: "https://server.smithery.ai/.well-known/jwks.json" */
11
- jwksUrl?: string;
12
- /** Optional explicit token path. Overrides basePath+"token". */
13
- tokenPath?: string;
14
- /** Handle a JWT grant provided by an external identity provider (i.e., Smithery) and mint access tokens */
15
- handleJwtGrant: (claims: IdentityJwtClaims, req: Request) => Promise<OAuthTokens | null>;
16
- }
17
- export declare function createIdentityTokenRouter(options: IdentityHandler): Router;
18
- export declare function mountIdentity(app: Application, options: IdentityHandler): void;
@@ -1,55 +0,0 @@
1
- import express from "express";
2
- import { createRemoteJWKSet, jwtVerify } from "jose";
3
- function normalizeBasePath(basePath) {
4
- const value = basePath ?? "/";
5
- return value.endsWith("/") ? value : `${value}/`;
6
- }
7
- export function createIdentityTokenRouter(options) {
8
- const basePath = normalizeBasePath(options.basePath);
9
- const issuer = options.issuer ?? "https://server.smithery.ai";
10
- const jwksUrl = new URL(options.jwksUrl ?? "https://server.smithery.ai/.well-known/jwks.json");
11
- const tokenPath = typeof options.tokenPath === "string" && options.tokenPath.length > 0
12
- ? options.tokenPath
13
- : `${basePath}token`;
14
- // Create JWKS resolver once; jose caches keys internally
15
- const JWKS = createRemoteJWKSet(jwksUrl);
16
- const tokenRouter = express.Router();
17
- // urlencoded parser required for OAuth token requests
18
- tokenRouter.use(express.urlencoded({ extended: false }));
19
- tokenRouter.post(tokenPath, async (req, res, next) => {
20
- try {
21
- const grantType = typeof req.body?.grant_type === "string"
22
- ? req.body.grant_type
23
- : undefined;
24
- if (grantType !== "urn:ietf:params:oauth:grant-type:jwt-bearer")
25
- return next();
26
- const assertion = typeof req.body?.assertion === "string" ? req.body.assertion : undefined;
27
- if (!assertion) {
28
- res.status(400).json({
29
- error: "invalid_request",
30
- error_description: "Missing assertion",
31
- });
32
- return;
33
- }
34
- const host = req.get("host") ?? "localhost";
35
- const audience = `https://${host}${tokenPath}`;
36
- const { payload } = await jwtVerify(assertion, JWKS, {
37
- issuer,
38
- audience,
39
- algorithms: ["RS256"],
40
- });
41
- const result = await options.handleJwtGrant(payload, req);
42
- if (!result)
43
- return next();
44
- res.json(result);
45
- }
46
- catch (error) {
47
- console.error(error);
48
- res.status(400).json({ error: "invalid_grant" });
49
- }
50
- });
51
- return tokenRouter;
52
- }
53
- export function mountIdentity(app, options) {
54
- app.use(createIdentityTokenRouter(options));
55
- }
@@ -1,21 +0,0 @@
1
- import type { OAuthServerProvider, OAuthTokenVerifier } from "@modelcontextprotocol/sdk/server/auth/provider.js";
2
- import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
3
- import type { Application, Response } from "express";
4
- import { type IdentityHandler } from "./identity.js";
5
- export interface TokenVerifier extends OAuthTokenVerifier {
6
- verifyAccessToken: (token: string) => Promise<AuthInfo>;
7
- requiredScopes?: string[];
8
- resourceMetadataUrl?: string;
9
- }
10
- type ProviderVerifier = OAuthServerProvider & TokenVerifier;
11
- export interface OAuthProvider extends ProviderVerifier {
12
- basePath?: string;
13
- callbackPath?: string;
14
- handleOAuthCallback?: (code: string, state: string | undefined, res: Response) => Promise<URL>;
15
- }
16
- export interface OAuthMountOptions {
17
- provider?: OAuthProvider | TokenVerifier;
18
- identity?: IdentityHandler;
19
- }
20
- export declare function mountOAuth(app: Application, opts: OAuthMountOptions): void;
21
- export {};
@@ -1,155 +0,0 @@
1
- import { authorizationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js";
2
- import { metadataHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/metadata.js";
3
- import { clientRegistrationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/register.js";
4
- import { revocationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/revoke.js";
5
- import { tokenHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/token.js";
6
- import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
7
- import { createOAuthMetadata, mcpAuthMetadataRouter, } from "@modelcontextprotocol/sdk/server/auth/router.js";
8
- import { mountIdentity } from "./identity.js";
9
- function isOAuthProvider(provider) {
10
- return !!provider && "authorize" in provider;
11
- }
12
- export function mountOAuth(app, opts) {
13
- // Determine base path once based on OAuth provider or identity
14
- const provider = opts.provider;
15
- const hasOAuth = isOAuthProvider(provider);
16
- const rawBasePath = hasOAuth
17
- ? (provider.basePath ?? "/")
18
- : (opts.identity?.basePath ?? "/");
19
- const basePath = rawBasePath.endsWith("/") ? rawBasePath : `${rawBasePath}/`;
20
- // Precompute endpoint pathnames from metadata
21
- let authorizationPath;
22
- let tokenPath;
23
- let registrationPath;
24
- let revocationPath;
25
- if (isOAuthProvider(provider)) {
26
- const placeholderIssuer = new URL("https://localhost");
27
- const placeholderBaseUrl = new URL(basePath, placeholderIssuer);
28
- const localMetadata = createOAuthMetadata({
29
- provider,
30
- issuerUrl: placeholderIssuer,
31
- baseUrl: placeholderBaseUrl,
32
- });
33
- authorizationPath = new URL(localMetadata.authorization_endpoint).pathname;
34
- tokenPath = new URL(localMetadata.token_endpoint).pathname;
35
- if (localMetadata.registration_endpoint) {
36
- registrationPath = new URL(localMetadata.registration_endpoint).pathname;
37
- }
38
- if (localMetadata.revocation_endpoint) {
39
- revocationPath = new URL(localMetadata.revocation_endpoint).pathname;
40
- }
41
- }
42
- // Metadata endpoints
43
- if (isOAuthProvider(provider)) {
44
- // Mount a per-request adapter so issuer/baseUrl reflect Host/Proto
45
- app.use((req, res, next) => {
46
- if (!req.path.startsWith("/.well-known/"))
47
- return next();
48
- const host = req.get("host") ?? "localhost";
49
- if (req.protocol !== "https") {
50
- console.warn("Detected http but using https for issuer URL in OAuth metadata since it will fail otherwise.");
51
- }
52
- const issuerUrl = new URL(`https://${host}`);
53
- const baseUrl = new URL(basePath, issuerUrl);
54
- const oauthMetadata = createOAuthMetadata({
55
- provider,
56
- issuerUrl,
57
- baseUrl,
58
- });
59
- if (opts.identity) {
60
- oauthMetadata.grant_types_supported = Array.from(new Set([
61
- ...(oauthMetadata.grant_types_supported ?? []),
62
- "urn:ietf:params:oauth:grant-type:jwt-bearer",
63
- ]));
64
- }
65
- const resourceServerUrl = new URL("/mcp", issuerUrl);
66
- const metadataRouter = mcpAuthMetadataRouter({
67
- oauthMetadata,
68
- resourceServerUrl,
69
- });
70
- return metadataRouter(req, res, next);
71
- });
72
- }
73
- else if (opts.identity) {
74
- // Identity-only: explicitly mount protected resource metadata endpoint
75
- app.use("/.well-known/oauth-protected-resource", (req, res, next) => {
76
- const host = req.get("host") ?? "localhost";
77
- const issuerUrl = new URL(`https://${host}`);
78
- const protectedResourceMetadata = {
79
- resource: new URL("/mcp", issuerUrl).href,
80
- authorization_servers: [issuerUrl.href],
81
- };
82
- return metadataHandler(protectedResourceMetadata)(req, res, next);
83
- });
84
- // Identity-only: also advertise minimal AS metadata for discovery per RFC 8414
85
- app.use("/.well-known/oauth-authorization-server", (req, res, next) => {
86
- const host = req.get("host") ?? "localhost";
87
- const issuerUrl = new URL(`https://${host}`);
88
- const oauthMetadata = {
89
- issuer: issuerUrl.href,
90
- token_endpoint: new URL(`${basePath}token`, issuerUrl).href,
91
- grant_types_supported: ["urn:ietf:params:oauth:grant-type:jwt-bearer"],
92
- };
93
- return metadataHandler(oauthMetadata)(req, res, next);
94
- });
95
- }
96
- // Mount identity (JWT bearer grant) first so OAuth token can fall through
97
- if (opts.identity) {
98
- const identityOptions = {
99
- ...opts.identity,
100
- basePath,
101
- tokenPath: tokenPath ?? `${basePath}token`,
102
- };
103
- mountIdentity(app, identityOptions);
104
- }
105
- // Mount OAuth endpoints functionally if an OAuth provider is present
106
- if (isOAuthProvider(provider)) {
107
- // Authorization endpoint
108
- const authPath = authorizationPath ?? `${basePath}authorize`;
109
- app.use(authPath, authorizationHandler({ provider }));
110
- // Token endpoint (OAuth); identity's token handler will handle JWT grant and call next() otherwise
111
- const tokPath = tokenPath ?? `${basePath}token`;
112
- app.use(tokPath, tokenHandler({ provider }));
113
- // Dynamic client registration if supported
114
- if (provider.clientsStore?.registerClient) {
115
- const regPath = registrationPath ?? `${basePath}register`;
116
- app.use(regPath, clientRegistrationHandler({ clientsStore: provider.clientsStore }));
117
- }
118
- // Token revocation if supported
119
- if (provider.revokeToken) {
120
- const revPath = revocationPath ?? `${basePath}revoke`;
121
- app.use(revPath, revocationHandler({ provider }));
122
- }
123
- // Optional OAuth callback
124
- const callbackHandler = provider.handleOAuthCallback?.bind(provider);
125
- if (callbackHandler) {
126
- const callbackPath = provider.callbackPath ?? "/callback";
127
- app.get(callbackPath, async (req, res) => {
128
- const code = typeof req.query.code === "string" ? req.query.code : undefined;
129
- const state = typeof req.query.state === "string" ? req.query.state : undefined;
130
- if (!code) {
131
- res.status(400).send("Invalid request parameters");
132
- return;
133
- }
134
- try {
135
- const redirectUrl = await callbackHandler(code, state, res);
136
- res.redirect(redirectUrl.toString());
137
- }
138
- catch (error) {
139
- console.error(error);
140
- res.status(500).send("Error during authentication callback");
141
- }
142
- });
143
- }
144
- }
145
- // Protect MCP resource with bearer auth if a verifier/provider is present
146
- if (provider) {
147
- app.use("/mcp", (req, res, next) => {
148
- return requireBearerAuth({
149
- verifier: provider,
150
- requiredScopes: provider.requiredScopes,
151
- resourceMetadataUrl: provider.resourceMetadataUrl,
152
- })(req, res, next);
153
- });
154
- }
155
- }
@@ -1,5 +0,0 @@
1
- export * from "./stateful.js";
2
- export * from "./stateless.js";
3
- export * from "./session.js";
4
- export * from "./auth/oauth.js";
5
- export * from "./auth/identity.js";
@@ -1,5 +0,0 @@
1
- export * from "./stateful.js";
2
- export * from "./stateless.js";
3
- export * from "./session.js";
4
- export * from "./auth/oauth.js";
5
- export * from "./auth/identity.js";
@@ -1,17 +0,0 @@
1
- import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
2
- export interface SessionStore<T extends Transport> {
3
- /** return existing transport (or `undefined`) */
4
- get(id: string): T | undefined;
5
- /** insert / update */
6
- set(id: string, t: T): void;
7
- /** optional - explicit eviction */
8
- delete?(id: string): void;
9
- }
10
- /**
11
- * Minimal Map‑based LRU implementation that fulfils {@link SessionStore}.
12
- * Keeps at most `max` transports; upon insert, the least‑recently‑used entry
13
- * (oldest insertion order) is removed and the evicted transport is closed.
14
- *
15
- * @param max maximum number of sessions to retain (default = 1000)
16
- */
17
- export declare const createLRUStore: <T extends Transport>(max?: number) => SessionStore<T>;
@@ -1,36 +0,0 @@
1
- /**
2
- * Minimal Map‑based LRU implementation that fulfils {@link SessionStore}.
3
- * Keeps at most `max` transports; upon insert, the least‑recently‑used entry
4
- * (oldest insertion order) is removed and the evicted transport is closed.
5
- *
6
- * @param max maximum number of sessions to retain (default = 1000)
7
- */
8
- export const createLRUStore = (max = 1000) => {
9
- // ECMA‑262 §23.1.3.13 - the order of keys in a Map object is the order of insertion; operations that remove a key drop it from that order, and set appends when the key is new or has just been removed.
10
- const cache = new Map();
11
- return {
12
- get: id => {
13
- const t = cache.get(id);
14
- if (!t)
15
- return undefined;
16
- // refresh position
17
- cache.delete(id);
18
- cache.set(id, t);
19
- return t;
20
- },
21
- set: (id, transport) => {
22
- if (cache.has(id)) {
23
- // key already present - refresh position
24
- cache.delete(id);
25
- }
26
- else if (cache.size >= max) {
27
- // evict oldest entry (first in insertion order)
28
- const [lruId, lruTransport] = cache.entries().next().value;
29
- lruTransport.close?.();
30
- cache.delete(lruId);
31
- }
32
- cache.set(id, transport);
33
- },
34
- delete: id => cache.delete(id),
35
- };
36
- };
@@ -1,42 +0,0 @@
1
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
2
- import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
3
- import express from "express";
4
- import type { z } from "zod";
5
- import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
- import { type SessionStore } from "./session.js";
7
- /**
8
- * Arguments when we create a new instance of your server
9
- */
10
- export interface CreateServerArg<T = Record<string, unknown>> {
11
- sessionId: string;
12
- config: T;
13
- auth?: AuthInfo;
14
- }
15
- export type CreateServerFn<T = Record<string, unknown>> = (arg: CreateServerArg<T>) => Server;
16
- /**
17
- * Configuration options for the stateful server
18
- */
19
- export interface StatefulServerOptions<T = Record<string, unknown>> {
20
- /**
21
- * Session store to use for managing active sessions
22
- */
23
- sessionStore?: SessionStore<StreamableHTTPServerTransport>;
24
- /**
25
- * Zod schema for config validation
26
- */
27
- schema?: z.ZodSchema<T>;
28
- /**
29
- * Express app instance to use (optional)
30
- */
31
- app?: express.Application;
32
- }
33
- /**
34
- * Creates a stateful server for handling MCP requests.
35
- * For every new session, we invoke createMcpServer to create a new instance of the server.
36
- * @param createMcpServer Function to create an MCP server
37
- * @param options Configuration options including optional schema validation and Express app
38
- * @returns Express app
39
- */
40
- export declare function createStatefulServer<T = Record<string, unknown>>(createMcpServer: CreateServerFn<T>, options?: StatefulServerOptions<T>): {
41
- app: express.Application;
42
- };
@@ -1,155 +0,0 @@
1
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
2
- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
3
- import express from "express";
4
- import { randomUUID } from "node:crypto";
5
- import { parseAndValidateConfig } from "../shared/config.js";
6
- import { zodToJsonSchema } from "zod-to-json-schema";
7
- import { createLRUStore } from "./session.js";
8
- /**
9
- * Creates a stateful server for handling MCP requests.
10
- * For every new session, we invoke createMcpServer to create a new instance of the server.
11
- * @param createMcpServer Function to create an MCP server
12
- * @param options Configuration options including optional schema validation and Express app
13
- * @returns Express app
14
- */
15
- export function createStatefulServer(createMcpServer, options) {
16
- const app = options?.app ?? express();
17
- app.use("/mcp", express.json());
18
- const sessionStore = options?.sessionStore ?? createLRUStore();
19
- // Handle POST requests for client-to-server communication
20
- app.post("/mcp", async (req, res) => {
21
- // Check for existing session ID
22
- const sessionId = req.headers["mcp-session-id"];
23
- let transport;
24
- if (sessionId && sessionStore.get(sessionId)) {
25
- // Reuse existing transport
26
- // biome-ignore lint/style/noNonNullAssertion: Not possible
27
- transport = sessionStore.get(sessionId);
28
- }
29
- else if (!sessionId && isInitializeRequest(req.body)) {
30
- // New initialization request
31
- const newSessionId = randomUUID();
32
- transport = new StreamableHTTPServerTransport({
33
- sessionIdGenerator: () => newSessionId,
34
- onsessioninitialized: sessionId => {
35
- // Store the transport by session ID
36
- sessionStore.set(sessionId, transport);
37
- },
38
- });
39
- // Clean up transport when closed
40
- transport.onclose = () => {
41
- if (transport.sessionId) {
42
- sessionStore.delete?.(transport.sessionId);
43
- }
44
- };
45
- // New session - validate config
46
- const configResult = parseAndValidateConfig(req, options?.schema);
47
- if (!configResult.ok) {
48
- const status = configResult.error.status || 400;
49
- res.status(status).json(configResult.error);
50
- return;
51
- }
52
- const config = configResult.value;
53
- try {
54
- const server = createMcpServer({
55
- sessionId: newSessionId,
56
- config: config,
57
- auth: req.auth,
58
- });
59
- // Connect to the MCP server
60
- await server.connect(transport);
61
- }
62
- catch (error) {
63
- console.error("Error initializing server:", error);
64
- res.status(500).json({
65
- jsonrpc: "2.0",
66
- error: {
67
- code: -32603,
68
- message: "Error initializing server.",
69
- },
70
- id: null,
71
- });
72
- return;
73
- }
74
- }
75
- else {
76
- // Invalid request
77
- res.status(400).json({
78
- jsonrpc: "2.0",
79
- error: {
80
- code: -32000,
81
- message: "Session not found or expired",
82
- },
83
- id: null,
84
- });
85
- return;
86
- }
87
- // Handle the request
88
- await transport.handleRequest(req, res, req.body);
89
- });
90
- // Add .well-known/mcp-config endpoint for configuration discovery
91
- app.get("/.well-known/mcp-config", (req, res) => {
92
- // Set proper content type for JSON Schema
93
- res.set("Content-Type", "application/schema+json; charset=utf-8");
94
- const baseSchema = options?.schema
95
- ? zodToJsonSchema(options.schema)
96
- : {
97
- type: "object",
98
- properties: {},
99
- required: [],
100
- };
101
- const configSchema = {
102
- $schema: "https://json-schema.org/draft/2020-12/schema",
103
- $id: `${req.protocol}://${req.get("host")}/.well-known/mcp-config`,
104
- title: "MCP Session Configuration",
105
- description: "Schema for the /mcp endpoint configuration",
106
- "x-query-style": "dot+bracket",
107
- ...baseSchema,
108
- };
109
- res.json(configSchema);
110
- });
111
- // Handle GET requests for server-to-client notifications via SSE
112
- app.get("/mcp", async (req, res) => {
113
- const sessionId = req.headers["mcp-session-id"];
114
- if (!sessionId || !sessionStore.get(sessionId)) {
115
- res.status(400).send("Invalid or expired session ID");
116
- return;
117
- }
118
- // biome-ignore lint/style/noNonNullAssertion: Not possible
119
- const transport = sessionStore.get(sessionId);
120
- await transport.handleRequest(req, res);
121
- });
122
- // Handle DELETE requests for session termination
123
- // https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#session-management
124
- app.delete("/mcp", async (req, res) => {
125
- const sessionId = req.headers["mcp-session-id"];
126
- if (!sessionId) {
127
- res.status(400).json({
128
- jsonrpc: "2.0",
129
- error: {
130
- code: -32600,
131
- message: "Missing mcp-session-id header",
132
- },
133
- id: null,
134
- });
135
- return;
136
- }
137
- const transport = sessionStore.get(sessionId);
138
- if (!transport) {
139
- res.status(404).json({
140
- jsonrpc: "2.0",
141
- error: {
142
- code: -32000,
143
- message: "Session not found or expired",
144
- },
145
- id: null,
146
- });
147
- return;
148
- }
149
- // Close the transport
150
- transport.close?.();
151
- // Acknowledge session termination with 204 No Content
152
- res.status(204).end();
153
- });
154
- return { app };
155
- }
@@ -1,39 +0,0 @@
1
- import express from "express";
2
- import type { z } from "zod";
3
- import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
- import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
5
- import type { OAuthMountOptions } from "./auth/oauth.js";
6
- /**
7
- * Arguments when we create a stateless server instance
8
- */
9
- export interface CreateStatelessServerArg<T = Record<string, unknown>> {
10
- config: T;
11
- auth?: AuthInfo;
12
- }
13
- export type CreateStatelessServerFn<T = Record<string, unknown>> = (arg: CreateStatelessServerArg<T>) => Server;
14
- /**
15
- * Configuration options for the stateless server
16
- */
17
- export interface StatelessServerOptions<T = Record<string, unknown>> {
18
- /**
19
- * Zod schema for config validation
20
- */
21
- schema?: z.ZodSchema<T>;
22
- /**
23
- * Express app instance to use (optional)
24
- */
25
- app?: express.Application;
26
- oauth?: OAuthMountOptions;
27
- }
28
- /**
29
- * Creates a stateless server for handling MCP requests.
30
- * Each request creates a new server instance - no session state is maintained.
31
- * This is ideal for stateless API integrations and serverless environments.
32
- *
33
- * @param createMcpServer Function to create an MCP server
34
- * @param options Configuration options including optional schema validation and Express app
35
- * @returns Express app
36
- */
37
- export declare function createStatelessServer<T = Record<string, unknown>>(createMcpServer: CreateStatelessServerFn<T>, options?: StatelessServerOptions<T>): {
38
- app: express.Application;
39
- };
@@ -1,108 +0,0 @@
1
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
2
- import express from "express";
3
- import { parseAndValidateConfig } from "../shared/config.js";
4
- import { zodToJsonSchema } from "zod-to-json-schema";
5
- /**
6
- * Creates a stateless server for handling MCP requests.
7
- * Each request creates a new server instance - no session state is maintained.
8
- * This is ideal for stateless API integrations and serverless environments.
9
- *
10
- * @param createMcpServer Function to create an MCP server
11
- * @param options Configuration options including optional schema validation and Express app
12
- * @returns Express app
13
- */
14
- export function createStatelessServer(createMcpServer, options) {
15
- const app = options?.app ?? express();
16
- app.use("/mcp", express.json());
17
- // Handle POST requests for client-to-server communication
18
- app.post("/mcp", async (req, res) => {
19
- // In stateless mode, create a new instance of transport and server for each request
20
- // to ensure complete isolation. A single instance would cause request ID collisions
21
- // when multiple clients connect concurrently.
22
- try {
23
- // Validate config for all requests in stateless mode
24
- const configResult = parseAndValidateConfig(req, options?.schema);
25
- if (!configResult.ok) {
26
- const status = configResult.error.status || 400;
27
- res.status(status).json(configResult.error);
28
- return;
29
- }
30
- const config = configResult.value;
31
- // Create a fresh server instance for each request
32
- const server = createMcpServer({
33
- config,
34
- auth: req.auth,
35
- });
36
- // Create a new transport for this request (no session management)
37
- const transport = new StreamableHTTPServerTransport({
38
- sessionIdGenerator: undefined,
39
- });
40
- // Clean up resources when request closes
41
- res.on("close", () => {
42
- transport.close();
43
- server.close();
44
- });
45
- // Connect to the MCP server
46
- await server.connect(transport);
47
- // Handle the request directly
48
- await transport.handleRequest(req, res, req.body);
49
- }
50
- catch (error) {
51
- console.error("Error handling MCP request:", error);
52
- if (!res.headersSent) {
53
- res.status(500).json({
54
- jsonrpc: "2.0",
55
- error: {
56
- code: -32603,
57
- message: "Internal server error",
58
- },
59
- id: null,
60
- });
61
- }
62
- }
63
- });
64
- // SSE notifications not supported in stateless mode
65
- app.get("/mcp", async (_req, res) => {
66
- res.status(405).json({
67
- jsonrpc: "2.0",
68
- error: {
69
- code: -32000,
70
- message: "Method not allowed.",
71
- },
72
- id: null,
73
- });
74
- });
75
- // Session termination not needed in stateless mode
76
- app.delete("/mcp", async (_req, res) => {
77
- res.status(405).json({
78
- jsonrpc: "2.0",
79
- error: {
80
- code: -32000,
81
- message: "Method not allowed.",
82
- },
83
- id: null,
84
- });
85
- });
86
- // Add .well-known/mcp-config endpoint for configuration discovery
87
- app.get("/.well-known/mcp-config", (req, res) => {
88
- // Set proper content type for JSON Schema
89
- res.set("Content-Type", "application/schema+json; charset=utf-8");
90
- const baseSchema = options?.schema
91
- ? zodToJsonSchema(options.schema)
92
- : {
93
- type: "object",
94
- properties: {},
95
- required: [],
96
- };
97
- const configSchema = {
98
- $schema: "https://json-schema.org/draft/2020-12/schema",
99
- $id: `${req.protocol}://${req.get("host")}/.well-known/mcp-config`,
100
- title: "MCP Session Configuration",
101
- description: "Schema for the /mcp endpoint configuration",
102
- "x-query-style": "dot+bracket",
103
- ...baseSchema,
104
- };
105
- res.json(configSchema);
106
- });
107
- return { app };
108
- }
@@ -1,41 +0,0 @@
1
- import type { Request as ExpressRequest } from "express";
2
- import type { z } from "zod";
3
- export interface SmitheryUrlOptions {
4
- apiKey?: string;
5
- profile?: string;
6
- config?: object;
7
- }
8
- export declare function appendConfigAsDotParams(url: URL, config: unknown): void;
9
- /**
10
- * Creates a URL to connect to the Smithery MCP server.
11
- * @param baseUrl The base URL of the Smithery server
12
- * @param options Optional configuration object
13
- * @returns A URL with config encoded using dot-notation query params (e.g. model.name=gpt-4&debug=true)
14
- */
15
- export declare function createSmitheryUrl(baseUrl: string, options?: SmitheryUrlOptions): URL;
16
- /**
17
- * Parses and validates config from an Express request with optional Zod schema validation
18
- * Supports dot-notation config parameters (e.g., foo=bar, a.b=c)
19
- * @param req The express request
20
- * @param schema Optional Zod schema for validation
21
- * @returns Result with either parsed data or error response
22
- */
23
- export declare function parseAndValidateConfig<T = Record<string, unknown>>(req: ExpressRequest, schema?: z.ZodSchema<T>): import("okay-error").Err<{
24
- readonly title: "Invalid configuration parameters";
25
- readonly status: 422;
26
- readonly detail: "One or more config parameters are invalid.";
27
- readonly instance: string;
28
- readonly configSchema: import("zod-to-json-schema").JsonSchema7Type & {
29
- $schema?: string | undefined;
30
- definitions?: {
31
- [key: string]: import("zod-to-json-schema").JsonSchema7Type;
32
- } | undefined;
33
- };
34
- readonly errors: {
35
- param: string;
36
- pointer: string;
37
- reason: string;
38
- received: unknown;
39
- }[];
40
- }> | import("okay-error").Ok<T>;
41
- export declare function parseConfigFromQuery(query: Iterable<[string, unknown]>): Record<string, unknown>;
@@ -1,132 +0,0 @@
1
- import _ from "lodash";
2
- import { err, ok } from "okay-error";
3
- import { zodToJsonSchema } from "zod-to-json-schema";
4
- function isPlainObject(value) {
5
- return value !== null && typeof value === "object" && !Array.isArray(value);
6
- }
7
- export function appendConfigAsDotParams(url, config) {
8
- function add(pathParts, value) {
9
- if (Array.isArray(value)) {
10
- for (let index = 0; index < value.length; index++) {
11
- add([...pathParts, String(index)], value[index]);
12
- }
13
- return;
14
- }
15
- if (isPlainObject(value)) {
16
- for (const [key, nested] of Object.entries(value)) {
17
- add([...pathParts, key], nested);
18
- }
19
- return;
20
- }
21
- const key = pathParts.join(".");
22
- let stringValue;
23
- switch (typeof value) {
24
- case "string":
25
- stringValue = value;
26
- break;
27
- case "number":
28
- case "boolean":
29
- stringValue = String(value);
30
- break;
31
- default:
32
- stringValue = JSON.stringify(value);
33
- }
34
- url.searchParams.set(key, stringValue);
35
- }
36
- if (isPlainObject(config)) {
37
- for (const [key, value] of Object.entries(config)) {
38
- add([key], value);
39
- }
40
- }
41
- }
42
- /**
43
- * Creates a URL to connect to the Smithery MCP server.
44
- * @param baseUrl The base URL of the Smithery server
45
- * @param options Optional configuration object
46
- * @returns A URL with config encoded using dot-notation query params (e.g. model.name=gpt-4&debug=true)
47
- */
48
- export function createSmitheryUrl(baseUrl, options) {
49
- const url = new URL(`${baseUrl}/mcp`);
50
- if (options?.config) {
51
- appendConfigAsDotParams(url, options.config);
52
- }
53
- if (options?.apiKey) {
54
- url.searchParams.set("api_key", options.apiKey);
55
- }
56
- if (options?.profile) {
57
- url.searchParams.set("profile", options.profile);
58
- }
59
- return url;
60
- }
61
- /**
62
- * Parses and validates config from an Express request with optional Zod schema validation
63
- * Supports dot-notation config parameters (e.g., foo=bar, a.b=c)
64
- * @param req The express request
65
- * @param schema Optional Zod schema for validation
66
- * @returns Result with either parsed data or error response
67
- */
68
- export function parseAndValidateConfig(req, schema) {
69
- const config = parseConfigFromQuery(Object.entries(req.query));
70
- // Validate config against schema if provided
71
- if (schema) {
72
- const result = schema.safeParse(config);
73
- if (!result.success) {
74
- const jsonSchema = zodToJsonSchema(schema);
75
- const errors = result.error.issues.map(issue => {
76
- // Safely traverse the config object to get the received value
77
- let received = config;
78
- for (const key of issue.path) {
79
- if (received && typeof received === "object" && key in received) {
80
- received = received[key];
81
- }
82
- else {
83
- received = undefined;
84
- break;
85
- }
86
- }
87
- return {
88
- param: issue.path.join(".") || "root",
89
- pointer: `/${issue.path.join("/")}`,
90
- reason: issue.message,
91
- received,
92
- };
93
- });
94
- return err({
95
- title: "Invalid configuration parameters",
96
- status: 422,
97
- detail: "One or more config parameters are invalid.",
98
- instance: req.originalUrl,
99
- configSchema: jsonSchema,
100
- errors,
101
- });
102
- }
103
- return ok(result.data);
104
- }
105
- return ok(config);
106
- }
107
- // Process dot-notation config parameters from query parameters (foo=bar, a.b=c)
108
- // This allows URL params like ?server.host=localhost&server.port=8080&debug=true
109
- export function parseConfigFromQuery(query) {
110
- const config = {};
111
- for (const [key, value] of query) {
112
- // Skip reserved parameters
113
- if (key === "api_key" || key === "profile")
114
- continue;
115
- const pathParts = key.split(".");
116
- // Handle array values from Express query parsing
117
- const rawValue = Array.isArray(value) ? value[0] : value;
118
- if (typeof rawValue !== "string")
119
- continue;
120
- // Try to parse value as JSON (for booleans, numbers, objects)
121
- let parsedValue = rawValue;
122
- try {
123
- parsedValue = JSON.parse(rawValue);
124
- }
125
- catch {
126
- // If parsing fails, use the raw string value
127
- }
128
- // Use lodash's set method to handle nested paths
129
- _.set(config, pathParts, parsedValue);
130
- }
131
- return config;
132
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * Patches a function on an object
3
- * @param obj
4
- * @param key
5
- * @param patcher
6
- */
7
- export declare function patch<T extends {
8
- [P in K]: (...args: any[]) => any;
9
- }, K extends keyof T & string>(obj: T, key: K, patcher: (fn: T[K]) => T[K]): void;
10
- export declare function patch<T extends {
11
- [P in K]?: (...args: any[]) => any;
12
- }, K extends keyof T & string>(obj: T, key: K, patcher: (fn?: T[K]) => T[K]): void;
@@ -1,12 +0,0 @@
1
- /**
2
- * Patches a function on an object
3
- * @param obj
4
- * @param key
5
- * @param patcher
6
- */
7
- // Unified implementation (not type-checked by callers)
8
- export function patch(obj, key, patcher) {
9
- // If the property is actually a function, bind it; otherwise undefined
10
- const original = typeof obj[key] === "function" ? obj[key].bind(obj) : undefined;
11
- obj[key] = patcher(original);
12
- }