duckpond-mcp-server 0.2.3 → 0.2.4
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/dist/chunk-MPMUZFRC.js +2 -0
- package/dist/chunk-MPMUZFRC.js.map +1 -0
- package/dist/chunk-RFFLXQNB.js +48 -0
- package/dist/chunk-RFFLXQNB.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/server.js +1 -1
- package/dist/tools/index.d.ts +25 -16
- package/dist/tools/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-43NWQIU3.js +0 -2
- package/dist/chunk-43NWQIU3.js.map +0 -1
- package/dist/chunk-TAP5LWZ7.js +0 -48
- package/dist/chunk-TAP5LWZ7.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as i}from"./chunk-A3S6D44B.js";import{z as o}from"zod";var n=i.tools;function u(){return process.env.DUCKPOND_DEFAULT_USER}function c(r){let s=r||u();if(!s)throw new Error("userId is required. Either provide it in the request or set DUCKPOND_DEFAULT_USER environment variable.");return s}var l=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)"),sql:o.string().min(1).describe("SQL query to execute")}),f=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)"),sql:o.string().min(1).describe("SQL statement to execute (DDL/DML)")}),U=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),S=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),m=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),p=o.object({}),g={async query(r,s){let t=c(s.userId);n(`Tool: query for user ${t}`);let e=await r.query(t,s.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2)}]}},async execute(r,s){let t=c(s.userId);n(`Tool: execute for user ${t}`);let e=await r.execute(t,s.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2)}]}},async getUserStats(r,s){let t=c(s.userId);n(`Tool: getUserStats for user ${t}`);let e=await r.getUserStats(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2)}]}},isAttached(r,s){let t=c(s.userId);n(`Tool: isAttached for user ${t}`);let e=r.isAttached(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({attached:e.data,userId:t},null,2)}]}},async detachUser(r,s){let t=c(s.userId);n(`Tool: detachUser for user ${t}`);let e=await r.detachUser(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:`User ${t} detached successfully`},null,2)}]}},listUsers(r,s){n("Tool: listUsers");let t=r.listUsers();if(!t.success)throw new Error(t.error.message);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}]}}};export{u as a,c as b,l as c,f as d,U as e,S as f,m as g,p as h,g as i};
|
|
2
|
+
//# sourceMappingURL=chunk-MPMUZFRC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\nimport type { DuckPondServer } from \"../server-core\"\nimport { loggers } from \"../utils/logger\"\n\nconst log = loggers.tools\n\n/**\n * Get the default user ID from environment variable\n */\nexport function getDefaultUserId(): string | undefined {\n return process.env.DUCKPOND_DEFAULT_USER\n}\n\n/**\n * Resolve user ID from input or default\n * @throws Error if no user ID is available\n */\nexport function resolveUserId(inputUserId?: string): string {\n const userId = inputUserId || getDefaultUserId()\n if (!userId) {\n throw new Error(\n \"userId is required. Either provide it in the request or set DUCKPOND_DEFAULT_USER environment variable.\",\n )\n }\n return userId\n}\n\n/**\n * Zod schema for query tool\n */\nexport const querySchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n sql: z.string().min(1).describe(\"SQL query to execute\"),\n})\n\n/**\n * Zod schema for execute tool\n */\nexport const executeSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n sql: z.string().min(1).describe(\"SQL statement to execute (DDL/DML)\"),\n})\n\n/**\n * Zod schema for getUserStats tool\n */\nexport const getUserStatsSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for isAttached tool\n */\nexport const isAttachedSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for detachUser tool\n */\nexport const detachUserSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for listUsers tool\n */\nexport const listUsersSchema = z.object({})\n\n/**\n * Tool implementations for MCP server\n */\nexport const tools = {\n /**\n * Execute a SQL query for a user\n */\n async query(server: DuckPondServer, input: z.infer<typeof querySchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: query for user ${userId}`)\n const result = await server.query(userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Execute DDL/DML statement\n */\n async execute(server: DuckPondServer, input: z.infer<typeof executeSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: execute for user ${userId}`)\n const result = await server.execute(userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Get user database statistics\n */\n async getUserStats(server: DuckPondServer, input: z.infer<typeof getUserStatsSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: getUserStats for user ${userId}`)\n const result = await server.getUserStats(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Check if user is attached\n */\n isAttached(server: DuckPondServer, input: z.infer<typeof isAttachedSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: isAttached for user ${userId}`)\n const result = server.isAttached(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n attached: result.data,\n userId,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Detach a user from cache\n */\n async detachUser(server: DuckPondServer, input: z.infer<typeof detachUserSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: detachUser for user ${userId}`)\n const result = await server.detachUser(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: `User ${userId} detached successfully`,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * List all currently cached users\n */\n listUsers(server: DuckPondServer, _input: z.infer<typeof listUsersSchema>) {\n log(\"Tool: listUsers\")\n const result = server.listUsers()\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n }\n },\n}\n"],"mappings":"wCAAA,OAAS,KAAAA,MAAS,MAKlB,IAAMC,EAAMC,EAAQ,MAKb,S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AAyC,CAChF,IAAMV,EAASF,EAAcY,EAAM,MAAM,EACzCf,EAAI,6BAA6BK,CAAM,EAAE,EACzC,IAAMW,EAAS,MAAMF,EAAO,WAAWT,CAAM,EAE7C,GAAI,CAACW,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,QAAS,GACT,QAAS,QAAQX,CAAM,wBACzB,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,UAAUS,EAAwBG,EAAyC,CACzEjB,EAAI,iBAAiB,EACrB,IAAMgB,EAASF,EAAO,UAAU,EAEhC,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UAAUA,EAAO,KAAM,KAAM,CAAC,CAC3C,CACF,CACF,CACF,CACF","names":["z","log","loggers","getDefaultUserId","resolveUserId","inputUserId","userId","querySchema","z","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","tools","server","input","result","_input"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import{a as E}from"./chunk-SU42EK5H.js";import{b as m,c as O,d as I,e as T,f as $,g as A,h as P}from"./chunk-MPMUZFRC.js";import{b as C}from"./chunk-A3S6D44B.js";import{webcrypto as D}from"crypto";import{FastMCP as U}from"@jordanburke/fastmcp";import{createHash as j,randomBytes as _}from"crypto";import{createRequire as q}from"module";import*as w from"jsonwebtoken";import{URL as J}from"url";globalThis.crypto||(globalThis.crypto=D);var N=q(import.meta.url),b=N("../package.json"),u=C.fastmcp,k=process.env.DUCKPOND_JWT_SECRET||_(32).toString("hex"),v=process.env.DUCKPOND_JWT_EXPIRES_IN?parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN,10):365*24*60*60,y=new Map,f=new Map;function W(s){u("\u{1F680} Initializing FastMCP server...");let i=new E(s.config),h={name:"duckpond",version:b.version,health:{enabled:!0,path:"/health",status:200,message:JSON.stringify({status:"healthy",service:"duckpond-mcp-server",version:b.version,timestamp:new Date().toISOString()})}},o=s.oauth?.enabled||s.basicAuth?new U({...h,oauth:{enabled:!0,authorizationServer:{issuer:s.oauth?.issuer||`http://localhost:${s.port||3e3}`,authorizationEndpoint:`${s.oauth?.issuer||`http://localhost:${s.port||3e3}`}/oauth/authorize`,tokenEndpoint:`${s.oauth?.issuer||`http://localhost:${s.port||3e3}`}/oauth/token`,jwksUri:`${s.oauth?.issuer||`http://localhost:${s.port||3e3}`}/oauth/jwks`,registrationEndpoint:`${s.oauth?.issuer||`http://localhost:${s.port||3e3}`}/oauth/register`,responseTypesSupported:["code"],grantTypesSupported:["authorization_code"],tokenEndpointAuthMethodsSupported:["client_secret_post","client_secret_basic"],codeChallengeMethodsSupported:["S256","plain"]},protectedResource:{resource:process.env.DUCKPOND_OAUTH_RESOURCE||s.oauth?.resource||`${s.oauth?.issuer||`http://localhost:${s.port||3e3}`}/mcp`,authorizationServers:[s.oauth?.issuer||`http://localhost:${s.port||3e3}`]}},authenticate:t=>{let e=t.headers?.authorization,r=s.oauth?.issuer||`http://localhost:${s.port||3e3}`;if(!e)throw s.oauth?.enabled?new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required. Please authenticate via OAuth."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${r}/oauth/authorize", resource="${r}/.well-known/oauth-protected-resource"`}}):new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json"}});if(s.basicAuth&&e.startsWith("Basic ")){let c=Buffer.from(e.slice(6),"base64").toString("utf-8"),[a,d]=c.split(":");if(a===s.basicAuth.username&&d===s.basicAuth.password)return Promise.resolve({userId:s.basicAuth.userId||a,email:s.basicAuth.email||`${a}@example.com`,scope:"read write"});throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid username or password"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Basic realm="MCP"'}})}if(s.oauth?.enabled&&e.startsWith("Bearer ")){let c=e.slice(7);try{let a=w.verify(c,k);if(!a.sub||!a.iat||!a.exp)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid token structure"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid token structure"'}});let d=s.oauth?.resource||`${r}/mcp`;if(a.aud&&a.aud!==d)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Token audience mismatch"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Token audience mismatch"'}});return Promise.resolve({userId:a.sub,email:a.email||"",scope:a.scope||"read write"})}catch(a){throw a instanceof Response?a:new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid or expired token"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid or expired token"'}})}}throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid authorization header format"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${r}/oauth/authorize", resource="${r}/.well-known/oauth-protected-resource"`}})}}):new U(h);return o.addTool({name:"query",description:"Execute a SQL query for a specific user and return results",parameters:O,execute:async t=>{try{let e=m(t.userId),r=await i.query(e,t.sql);return r.success?JSON.stringify({rows:r.data,rowCount:r.data.length,executionTime:r.executionTime},null,2):`ERROR: ${r.error.message}`}catch(e){u("Error in query tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),o.addTool({name:"execute",description:"Execute SQL statement (DDL/DML) for a specific user without returning results",parameters:I,execute:async t=>{try{let e=m(t.userId),r=await i.execute(e,t.sql);return r.success?JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:r.executionTime},null,2):`ERROR: ${r.error.message}`}catch(e){u("Error in execute tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),o.addTool({name:"getUserStats",description:"Get statistics about a user's database (memory usage, query count, etc.)",parameters:T,execute:async t=>{try{let e=m(t.userId),r=await i.getUserStats(e);return r.success?JSON.stringify({...r.data,lastAccess:r.data.lastAccess.toISOString()},null,2):`ERROR: ${r.error.message}`}catch(e){u("Error in getUserStats tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),o.addTool({name:"isAttached",description:"Check if a user's database is currently cached in memory",parameters:$,execute:async t=>{try{let e=m(t.userId),r=i.isAttached(e);return r.success?JSON.stringify({attached:r.data,userId:e},null,2):`ERROR: ${r.error.message}`}catch(e){u("Error in isAttached tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),o.addTool({name:"detachUser",description:"Manually detach a user's database from the cache to free resources",parameters:A,execute:async t=>{try{let e=m(t.userId),r=await i.detachUser(e);return r.success?JSON.stringify({success:!0,message:`User ${e} detached successfully`},null,2):`ERROR: ${r.error.message}`}catch(e){u("Error in detachUser tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),o.addTool({name:"listUsers",description:"List all currently cached users and cache statistics",parameters:P,execute:async()=>{try{let t=i.listUsers();return t.success?JSON.stringify(t.data,null,2):`ERROR: ${t.error.message}`}catch(t){u("Error in listUsers tool:",t);let e=t instanceof Error?t.message:String(t);return`ERROR: ${JSON.stringify({error:e},null,2)}`}}}),s.oauth?.enabled&&F(o,s),o.getApp().get("/",t=>{let e=s.oauth?.issuer||`http://localhost:${s.port||3e3}`,r={name:"DuckPond MCP Server",version:b.version,description:"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage",service:"duckpond-mcp-server",capabilities:{tools:["query","execute","getUserStats","isAttached","detachUser","listUsers"],transports:["stdio","http"],authentication:{oauth:s.oauth?.enabled||!1,basicAuth:!!s.basicAuth}},endpoints:{mcp:`${e}${s.endpoint||"/mcp"}`,health:`${e}/health`,...s.oauth?.enabled&&{oauth:{authorization:`${e}/oauth/authorize`,token:`${e}/oauth/token`,jwks:`${e}/oauth/jwks`,register:`${e}/oauth/register`}}},timestamp:new Date().toISOString()};return t.json(r)}),u("\u2713 FastMCP server created"),{server:o,duckpond:i}}function F(s,i){let h=s.getApp();setInterval(()=>{let o=Date.now();for(let[n,t]of y.entries())o-t.createdAt>6e5&&y.delete(n);for(let[n,t]of f.entries())o-t.createdAt>2592e6&&f.delete(n)},6e4),h.get("/oauth/authorize",o=>{let n=o.req.query(),t=n.response_type,e=n.redirect_uri,r=n.state,c=n.code_challenge,a=n.code_challenge_method,d=n.client_id;if(t!=="code")return o.json({error:"unsupported_response_type",error_description:"Only 'code' response type is supported"},400);if(!e)return o.json({error:"invalid_request",error_description:"redirect_uri is required"},400);if(c&&(!a||!["S256","plain"].includes(a)))return o.json({error:"invalid_request",error_description:"Invalid code_challenge_method. Only 'S256' and 'plain' are supported"},400);let l=`
|
|
2
|
+
<!DOCTYPE html>
|
|
3
|
+
<html>
|
|
4
|
+
<head>
|
|
5
|
+
<title>OAuth Login - DuckPond MCP Server</title>
|
|
6
|
+
<style>
|
|
7
|
+
body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }
|
|
8
|
+
.form-group { margin-bottom: 15px; }
|
|
9
|
+
label { display: block; margin-bottom: 5px; font-weight: bold; }
|
|
10
|
+
input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
|
|
11
|
+
button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
|
|
12
|
+
button:hover { background: #005a87; }
|
|
13
|
+
.app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }
|
|
14
|
+
</style>
|
|
15
|
+
</head>
|
|
16
|
+
<body>
|
|
17
|
+
<div class="app-info">
|
|
18
|
+
<h3>\u{1F510} OAuth Authorization</h3>
|
|
19
|
+
<p><strong>Application:</strong> ${d||"MCP Client"}</p>
|
|
20
|
+
<p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>
|
|
21
|
+
</div>
|
|
22
|
+
|
|
23
|
+
<form method="POST" action="/oauth/authorize">
|
|
24
|
+
<input type="hidden" name="response_type" value="${t}">
|
|
25
|
+
<input type="hidden" name="redirect_uri" value="${e}">
|
|
26
|
+
<input type="hidden" name="state" value="${r||""}">
|
|
27
|
+
<input type="hidden" name="code_challenge" value="${c||""}">
|
|
28
|
+
<input type="hidden" name="code_challenge_method" value="${a||""}">
|
|
29
|
+
<input type="hidden" name="client_id" value="${d||""}">
|
|
30
|
+
|
|
31
|
+
<div class="form-group">
|
|
32
|
+
<label for="username">Username:</label>
|
|
33
|
+
<input type="text" id="username" name="username" required>
|
|
34
|
+
</div>
|
|
35
|
+
|
|
36
|
+
<div class="form-group">
|
|
37
|
+
<label for="password">Password:</label>
|
|
38
|
+
<input type="password" id="password" name="password" required>
|
|
39
|
+
</div>
|
|
40
|
+
|
|
41
|
+
<button type="submit">Authorize Application</button>
|
|
42
|
+
</form>
|
|
43
|
+
</body>
|
|
44
|
+
</html>`;return o.html(l)}),h.post("/oauth/authorize",async o=>{try{let n=await o.req.text(),t=new URLSearchParams(n),e=t.get("username"),r=t.get("password"),c=t.get("redirect_uri"),a=t.get("state"),d=t.get("code_challenge"),l=t.get("code_challenge_method");if(e!==i.oauth?.username||r!==i.oauth?.password)return o.html(`
|
|
45
|
+
<!DOCTYPE html>
|
|
46
|
+
<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>
|
|
47
|
+
<body><div class="error">\u274C Invalid username or password</div><a href="javascript:history.back()">\u2190 Try Again</a></body></html>`,401);let S=_(16).toString("hex");y.set(S,{createdAt:Date.now(),redirectUri:c||"",codeChallenge:d||void 0,codeChallengeMethod:l||void 0,userId:i.oauth?.userId||e||"oauth-user"});let g=new J(c||"");return g.searchParams.set("code",S),a&&g.searchParams.set("state",a),o.redirect(g.toString(),302)}catch{return o.json({error:"invalid_request",error_description:"Failed to process authorization request"},400)}}),h.post("/oauth/token",async o=>{let n=await o.req.text(),t=new URLSearchParams(n),e=t.get("grant_type"),r=t.get("code"),c=t.get("redirect_uri"),a=t.get("code_verifier"),d=t.get("refresh_token");if(e==="refresh_token"){if(!d)return o.json({error:"invalid_request",error_description:"refresh_token is required for refresh_token grant type"},400);let p=f.get(d);if(!p)return o.json({error:"invalid_grant",error_description:"Invalid or expired refresh token"},400);f.delete(d);let M={sub:p.userId,email:p.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+v,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},R=_(32).toString("hex");f.set(R,{createdAt:Date.now(),userId:p.userId,email:p.email});let z=w.sign(M,k);return o.json({access_token:z,token_type:"Bearer",expires_in:v,scope:"read write",refresh_token:R})}if(e!=="authorization_code")return o.json({error:"unsupported_grant_type",error_description:"Only 'authorization_code' and 'refresh_token' grant types are supported"},400);let l=y.get(r||"");if(!l)return o.json({error:"invalid_grant",error_description:"Invalid or expired authorization code"},400);if(l.redirectUri&&l.redirectUri!==c)return o.json({error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(l.codeChallenge){if(!a)return o.json({error:"invalid_grant",error_description:"code_verifier is required when code_challenge was used"},400);let p;if(l.codeChallengeMethod==="S256"?p=j("sha256").update(a).digest().toString("base64url"):p=a,p!==l.codeChallenge)return o.json({error:"invalid_grant",error_description:"Invalid code_verifier"},400)}y.delete(r);let S={sub:l.userId,email:i.oauth?.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+v,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},g=_(32).toString("hex");f.set(g,{createdAt:Date.now(),userId:l.userId,email:i.oauth?.email});let x=w.sign(S,k);return o.json({access_token:x,token_type:"Bearer",expires_in:v,scope:"read write",refresh_token:g})}),h.get("/oauth/jwks",o=>o.json({keys:[{kty:"oct",use:"sig",kid:"duckpond-hmac-key",alg:"HS256"}]})),h.post("/oauth/register",async o=>{try{let n={};try{let c=await o.req.text();if(c&&c!=="[object Object]")try{n=JSON.parse(c)}catch{n=Object.fromEntries(new URLSearchParams(c))}}catch(c){u("Error parsing request body:",c)}let t=`client-${_(8).toString("hex")}`,e=_(16).toString("hex"),r={client_id:t,client_secret:e,client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:n.grant_types||["authorization_code"],response_types:n.response_types||["code"],redirect_uris:n.redirect_uris||[],token_endpoint_auth_method:n.token_endpoint_auth_method||"client_secret_post"};return n.client_name&&(r.client_name=n.client_name),n.scope&&(r.scope=n.scope),o.json(r,201)}catch(n){return o.json({error:"invalid_client_metadata",error_description:"Invalid client registration request: "+(n instanceof Error?n.message:String(n))},400)}}),u("\u2713 OAuth flow endpoints added")}async function Z(s,i){let{server:h,duckpond:o}=W(s),n=await o.init();if(!n.success)throw new Error(`Failed to initialize DuckPond: ${n.error.message}`);u("DuckPond initialized successfully"),i==="stdio"?(await h.start({transportType:"stdio"}),u("\u2713 FastMCP server running with stdio transport")):(await h.start({transportType:"httpStream",httpStream:{port:s.port||3e3,endpoint:s.endpoint||"/mcp"}}),u(`\u2713 FastMCP server running on http://0.0.0.0:${s.port||3e3}${s.endpoint||"/mcp"}`),u("\u{1F50C} Connect with StreamableHTTPClientTransport")),process.on("SIGINT",async()=>{u("Received SIGINT, closing server..."),await o.close(),process.exit(0)}),process.on("SIGTERM",async()=>{u("Received SIGTERM, closing server..."),await o.close(),process.exit(0)})}export{W as a,Z as b};
|
|
48
|
+
//# sourceMappingURL=chunk-RFFLXQNB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { FastMCP } from \"@jordanburke/fastmcp\"\nimport { createHash, randomBytes } from \"crypto\"\nimport { createRequire } from \"module\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport * as jwt from \"jsonwebtoken\"\nimport { URL } from \"url\"\nimport { z } from \"zod\"\n\nimport { DuckPondServer, type DuckPondServerConfig } from \"./server-core\"\nimport {\n detachUserSchema,\n executeSchema,\n getDefaultUserId,\n getUserStatsSchema,\n isAttachedSchema,\n listUsersSchema,\n querySchema,\n resolveUserId,\n} from \"./tools\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.fastmcp\n\nexport type OAuthConfig = {\n enabled: boolean\n username: string\n password: string\n userId: string\n email?: string\n issuer?: string\n resource?: string\n}\n\nexport type FastMCPServerOptions = {\n config: DuckPondServerConfig\n port?: number\n endpoint?: string\n oauth?: OAuthConfig\n basicAuth?: {\n username: string\n password: string\n userId?: string\n email?: string\n }\n}\n\n// JWT secret for token signing/validation\nconst JWT_SECRET = process.env.DUCKPOND_JWT_SECRET || randomBytes(32).toString(\"hex\")\n\n// JWT token expiration configuration (default: 1 year)\nconst JWT_EXPIRES_IN = process.env.DUCKPOND_JWT_EXPIRES_IN\n ? parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN, 10)\n : 365 * 24 * 60 * 60 // 1 year in seconds\n\n// In-memory stores for OAuth flow\nconst authorizationCodes = new Map<\n string,\n {\n createdAt: number\n redirectUri?: string\n codeChallenge?: string\n codeChallengeMethod?: string\n userId: string\n }\n>()\n\nconst refreshTokens = new Map<\n string,\n {\n createdAt: number\n userId: string\n email?: string\n }\n>()\n\n// AuthSession type for FastMCP authentication\ntype AuthSession = {\n userId: string\n email: string\n scope: string\n [key: string]: unknown // Allow additional properties\n}\n\ntype OAuthClientRegistrationRequest = {\n grant_types?: string[]\n response_types?: string[]\n redirect_uris?: string[]\n token_endpoint_auth_method?: string\n client_name?: string\n scope?: string\n}\n\ntype OAuthClientRegistrationResponse = {\n client_id: string\n client_secret: string\n client_id_issued_at: number\n client_secret_expires_at: number\n grant_types: string[]\n response_types: string[]\n redirect_uris: string[]\n token_endpoint_auth_method: string\n client_name?: string\n scope?: string\n}\n\nexport function createFastMCPServer(options: FastMCPServerOptions): {\n server: FastMCP\n duckpond: DuckPondServer\n} {\n log(\"🚀 Initializing FastMCP server...\")\n\n // Create DuckPond server instance\n const duckpond = new DuckPondServer(options.config)\n\n // Build server configuration\n const baseConfig = {\n name: \"duckpond\",\n version: packageJson.version as `${number}.${number}.${number}`,\n health: {\n enabled: true,\n path: \"/health\",\n status: 200,\n message: JSON.stringify({\n status: \"healthy\",\n service: \"duckpond-mcp-server\",\n version: packageJson.version,\n timestamp: new Date().toISOString(),\n }),\n },\n }\n\n // Create server with authentication (OAuth, Basic Auth, or none)\n const server =\n options.oauth?.enabled || options.basicAuth\n ? new FastMCP<AuthSession>({\n ...baseConfig,\n oauth: {\n enabled: true,\n authorizationServer: {\n issuer: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n authorizationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/authorize`,\n tokenEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/token`,\n jwksUri: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/jwks`,\n registrationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/register`,\n responseTypesSupported: [\"code\"],\n grantTypesSupported: [\"authorization_code\"],\n tokenEndpointAuthMethodsSupported: [\"client_secret_post\", \"client_secret_basic\"],\n codeChallengeMethodsSupported: [\"S256\", \"plain\"],\n },\n protectedResource: {\n resource:\n process.env.DUCKPOND_OAUTH_RESOURCE ||\n options.oauth?.resource ||\n `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n authorizationServers: [options.oauth?.issuer || `http://localhost:${options.port || 3000}`],\n },\n },\n authenticate: (request) => {\n const authHeader = request.headers?.authorization\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n // For OAuth-enabled servers, require authentication\n if (!authHeader) {\n if (options.oauth?.enabled) {\n // Return HTTP 401 with WWW-Authenticate header for proper OAuth discovery\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required. Please authenticate via OAuth.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n }\n\n // For non-OAuth servers, also require some form of auth\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n )\n }\n\n // Handle Basic Authentication\n if (options.basicAuth && authHeader.startsWith(\"Basic \")) {\n const credentials = Buffer.from(authHeader.slice(6), \"base64\").toString(\"utf-8\")\n const [username, password] = credentials.split(\":\")\n\n if (username === options.basicAuth.username && password === options.basicAuth.password) {\n return Promise.resolve({\n userId: options.basicAuth.userId || username,\n email: options.basicAuth.email || `${username}@example.com`,\n scope: \"read write\",\n })\n } else {\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid username or password\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Basic realm=\"MCP\"`,\n },\n },\n )\n }\n }\n\n // Handle Bearer Token (OAuth) - Validate JWT\n if (options.oauth?.enabled && authHeader.startsWith(\"Bearer \")) {\n const token = authHeader.slice(7) // Remove 'Bearer ' prefix\n\n try {\n // Verify JWT token\n const decoded = jwt.verify(token, JWT_SECRET) as jwt.JwtPayload\n\n if (!decoded.sub || !decoded.iat || !decoded.exp) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid token structure\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid token structure\"`,\n },\n },\n )\n }\n\n // Validate audience\n const expectedAudience = options.oauth?.resource || `${baseUrl}/mcp`\n if (decoded.aud && decoded.aud !== expectedAudience) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Token audience mismatch\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Token audience mismatch\"`,\n },\n },\n )\n }\n\n // Return user info from JWT claims\n return Promise.resolve({\n userId: decoded.sub,\n email: (decoded.email as string) || \"\",\n scope: (decoded.scope as string) || \"read write\",\n })\n } catch (error) {\n if (error instanceof Response) {\n throw error // Re-throw our custom Response errors\n }\n\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid or expired token\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid or expired token\"`,\n },\n },\n )\n }\n }\n\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid authorization header format\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n },\n })\n : new FastMCP(baseConfig)\n\n // Add query tool\n server.addTool({\n name: \"query\",\n description: \"Execute a SQL query for a specific user and return results\",\n parameters: querySchema,\n execute: async (args) => {\n try {\n const userId = resolveUserId(args.userId)\n const result = await duckpond.query(userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in query tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add execute tool\n server.addTool({\n name: \"execute\",\n description: \"Execute SQL statement (DDL/DML) for a specific user without returning results\",\n parameters: executeSchema,\n execute: async (args) => {\n try {\n const userId = resolveUserId(args.userId)\n const result = await duckpond.execute(userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in execute tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add getUserStats tool\n server.addTool({\n name: \"getUserStats\",\n description: \"Get statistics about a user's database (memory usage, query count, etc.)\",\n parameters: getUserStatsSchema,\n execute: async (args) => {\n try {\n const userId = resolveUserId(args.userId)\n const result = await duckpond.getUserStats(userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in getUserStats tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add isAttached tool\n server.addTool({\n name: \"isAttached\",\n description: \"Check if a user's database is currently cached in memory\",\n parameters: isAttachedSchema,\n execute: async (args) => {\n try {\n const userId = resolveUserId(args.userId)\n const result = duckpond.isAttached(userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n attached: result.data,\n userId,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in isAttached tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add detachUser tool\n server.addTool({\n name: \"detachUser\",\n description: \"Manually detach a user's database from the cache to free resources\",\n parameters: detachUserSchema,\n execute: async (args) => {\n try {\n const userId = resolveUserId(args.userId)\n const result = await duckpond.detachUser(userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: `User ${userId} detached successfully`,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in detachUser tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add listUsers tool\n server.addTool({\n name: \"listUsers\",\n description: \"List all currently cached users and cache statistics\",\n parameters: listUsersSchema,\n execute: async () => {\n try {\n const result = duckpond.listUsers()\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(result.data, null, 2)\n } catch (error) {\n log(\"Error in listUsers tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add OAuth flow endpoints if OAuth is enabled\n if (options.oauth?.enabled) {\n setupOAuthEndpoints(server, options)\n }\n\n // Add root info endpoint using Hono\n const app = server.getApp()\n app.get(\"/\", (c) => {\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n const serverInfo = {\n name: \"DuckPond MCP Server\",\n version: packageJson.version,\n description: \"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage\",\n service: \"duckpond-mcp-server\",\n capabilities: {\n tools: [\"query\", \"execute\", \"getUserStats\", \"isAttached\", \"detachUser\", \"listUsers\"],\n transports: [\"stdio\", \"http\"],\n authentication: {\n oauth: options.oauth?.enabled || false,\n basicAuth: !!options.basicAuth,\n },\n },\n endpoints: {\n mcp: `${baseUrl}${options.endpoint || \"/mcp\"}`,\n health: `${baseUrl}/health`,\n ...(options.oauth?.enabled && {\n oauth: {\n authorization: `${baseUrl}/oauth/authorize`,\n token: `${baseUrl}/oauth/token`,\n jwks: `${baseUrl}/oauth/jwks`,\n register: `${baseUrl}/oauth/register`,\n },\n }),\n },\n timestamp: new Date().toISOString(),\n }\n\n return c.json(serverInfo)\n })\n\n log(\"✓ FastMCP server created\")\n\n return { server, duckpond }\n}\n\nfunction setupOAuthEndpoints(server: FastMCP, options: FastMCPServerOptions): void {\n const app = server.getApp()\n\n // Clean up old codes and refresh tokens every minute\n setInterval(() => {\n const now = Date.now()\n // Clean authorization codes (10 minutes)\n for (const [code, data] of authorizationCodes.entries()) {\n if (now - data.createdAt > 600000) {\n authorizationCodes.delete(code)\n }\n }\n // Clean refresh tokens (30 days)\n for (const [token, data] of refreshTokens.entries()) {\n if (now - data.createdAt > 2592000000) {\n refreshTokens.delete(token)\n }\n }\n }, 60000)\n\n // OAuth Authorization Endpoint - Login Form\n app.get(\"/oauth/authorize\", (c) => {\n const params = c.req.query()\n const responseType = params.response_type\n const redirectUri = params.redirect_uri\n const state = params.state\n const codeChallenge = params.code_challenge\n const codeChallengeMethod = params.code_challenge_method\n const clientId = params.client_id\n\n if (responseType !== \"code\") {\n return c.json(\n {\n error: \"unsupported_response_type\",\n error_description: \"Only 'code' response type is supported\",\n },\n 400,\n )\n }\n\n if (!redirectUri) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"redirect_uri is required\",\n },\n 400,\n )\n }\n\n // Validate PKCE parameters if present\n if (codeChallenge) {\n if (!codeChallengeMethod || ![\"S256\", \"plain\"].includes(codeChallengeMethod)) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Invalid code_challenge_method. Only 'S256' and 'plain' are supported\",\n },\n 400,\n )\n }\n }\n\n // Serve login form\n const loginForm = `\n<!DOCTYPE html>\n<html>\n<head>\n <title>OAuth Login - DuckPond MCP Server</title>\n <style>\n body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }\n .form-group { margin-bottom: 15px; }\n label { display: block; margin-bottom: 5px; font-weight: bold; }\n input[type=\"text\"], input[type=\"password\"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }\n button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }\n button:hover { background: #005a87; }\n .app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }\n </style>\n</head>\n<body>\n <div class=\"app-info\">\n <h3>🔐 OAuth Authorization</h3>\n <p><strong>Application:</strong> ${clientId || \"MCP Client\"}</p>\n <p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>\n </div>\n\n <form method=\"POST\" action=\"/oauth/authorize\">\n <input type=\"hidden\" name=\"response_type\" value=\"${responseType}\">\n <input type=\"hidden\" name=\"redirect_uri\" value=\"${redirectUri}\">\n <input type=\"hidden\" name=\"state\" value=\"${state || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge\" value=\"${codeChallenge || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge_method\" value=\"${codeChallengeMethod || \"\"}\">\n <input type=\"hidden\" name=\"client_id\" value=\"${clientId || \"\"}\">\n\n <div class=\"form-group\">\n <label for=\"username\">Username:</label>\n <input type=\"text\" id=\"username\" name=\"username\" required>\n </div>\n\n <div class=\"form-group\">\n <label for=\"password\">Password:</label>\n <input type=\"password\" id=\"password\" name=\"password\" required>\n </div>\n\n <button type=\"submit\">Authorize Application</button>\n </form>\n</body>\n</html>`\n\n return c.html(loginForm)\n })\n\n // OAuth Authorization POST - Process Login\n app.post(\"/oauth/authorize\", async (c) => {\n try {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n\n const username = params.get(\"username\")\n const password = params.get(\"password\")\n const redirectUri = params.get(\"redirect_uri\")\n const state = params.get(\"state\")\n const codeChallenge = params.get(\"code_challenge\")\n const codeChallengeMethod = params.get(\"code_challenge_method\")\n\n // Validate credentials\n if (username !== options.oauth?.username || password !== options.oauth?.password) {\n const errorForm = `\n<!DOCTYPE html>\n<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>\n<body><div class=\"error\">❌ Invalid username or password</div><a href=\"javascript:history.back()\">← Try Again</a></body></html>`\n return c.html(errorForm, 401)\n }\n\n // Generate authorization code\n const code = randomBytes(16).toString(\"hex\")\n authorizationCodes.set(code, {\n createdAt: Date.now(),\n redirectUri: redirectUri || \"\",\n codeChallenge: codeChallenge || undefined,\n codeChallengeMethod: codeChallengeMethod || undefined,\n userId: options.oauth?.userId || username || \"oauth-user\",\n })\n\n // Redirect with authorization code\n const redirectUrl = new URL(redirectUri || \"\")\n redirectUrl.searchParams.set(\"code\", code)\n if (state) {\n redirectUrl.searchParams.set(\"state\", state)\n }\n\n return c.redirect(redirectUrl.toString(), 302)\n } catch {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Failed to process authorization request\",\n },\n 400,\n )\n }\n })\n\n // OAuth Token Endpoint\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n const grantType = params.get(\"grant_type\")\n const code = params.get(\"code\")\n const redirectUri = params.get(\"redirect_uri\")\n const codeVerifier = params.get(\"code_verifier\")\n const refreshTokenParam = params.get(\"refresh_token\")\n\n if (grantType === \"refresh_token\") {\n // Handle refresh token flow\n if (!refreshTokenParam) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"refresh_token is required for refresh_token grant type\",\n },\n 400,\n )\n }\n\n const tokenData = refreshTokens.get(refreshTokenParam)\n if (!tokenData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired refresh token\",\n },\n 400,\n )\n }\n\n // Remove old refresh token (token rotation)\n refreshTokens.delete(refreshTokenParam)\n\n // Generate new JWT access token\n const accessTokenPayload = {\n sub: tokenData.userId,\n email: tokenData.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate new refresh token\n const newRefreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(newRefreshToken, {\n createdAt: Date.now(),\n userId: tokenData.userId,\n email: tokenData.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: newRefreshToken,\n })\n }\n\n if (grantType !== \"authorization_code\") {\n return c.json(\n {\n error: \"unsupported_grant_type\",\n error_description: \"Only 'authorization_code' and 'refresh_token' grant types are supported\",\n },\n 400,\n )\n }\n\n const codeData = authorizationCodes.get(code || \"\")\n if (!codeData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired authorization code\",\n },\n 400,\n )\n }\n\n // Validate redirect_uri matches\n if (codeData.redirectUri && codeData.redirectUri !== redirectUri) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"redirect_uri mismatch\",\n },\n 400,\n )\n }\n\n // Validate PKCE if code_challenge was provided\n if (codeData.codeChallenge) {\n if (!codeVerifier) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"code_verifier is required when code_challenge was used\",\n },\n 400,\n )\n }\n\n let expectedChallenge: string\n if (codeData.codeChallengeMethod === \"S256\") {\n expectedChallenge = createHash(\"sha256\").update(codeVerifier).digest().toString(\"base64url\")\n } else {\n // 'plain' method\n expectedChallenge = codeVerifier\n }\n\n if (expectedChallenge !== codeData.codeChallenge) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid code_verifier\",\n },\n 400,\n )\n }\n }\n\n // Remove used code\n authorizationCodes.delete(code!)\n\n // Generate JWT access token\n const accessTokenPayload = {\n sub: codeData.userId,\n email: options.oauth?.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate refresh token\n const refreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(refreshToken, {\n createdAt: Date.now(),\n userId: codeData.userId,\n email: options.oauth?.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: refreshToken,\n })\n })\n\n // JWKS Endpoint\n app.get(\"/oauth/jwks\", (c) => {\n return c.json({\n keys: [\n {\n kty: \"oct\", // Octet sequence for symmetric keys\n use: \"sig\",\n kid: \"duckpond-hmac-key\",\n alg: \"HS256\",\n },\n ],\n })\n })\n\n // Dynamic Client Registration\n app.post(\"/oauth/register\", async (c) => {\n try {\n let registrationRequest: OAuthClientRegistrationRequest = {}\n\n try {\n const body = await c.req.text()\n if (body && body !== \"[object Object]\") {\n try {\n registrationRequest = JSON.parse(body) as OAuthClientRegistrationRequest\n } catch {\n const formData = Object.fromEntries(new URLSearchParams(body))\n registrationRequest = formData as OAuthClientRegistrationRequest\n }\n }\n } catch (parseError) {\n log(\"Error parsing request body:\", parseError)\n }\n\n const clientId = `client-${randomBytes(8).toString(\"hex\")}`\n const clientSecret = randomBytes(16).toString(\"hex\")\n\n const response: OAuthClientRegistrationResponse = {\n client_id: clientId,\n client_secret: clientSecret,\n client_id_issued_at: Math.floor(Date.now() / 1000),\n client_secret_expires_at: 0, // Never expires\n grant_types: registrationRequest.grant_types || [\"authorization_code\"],\n response_types: registrationRequest.response_types || [\"code\"],\n redirect_uris: registrationRequest.redirect_uris || [],\n token_endpoint_auth_method: registrationRequest.token_endpoint_auth_method || \"client_secret_post\",\n }\n\n if (registrationRequest.client_name) {\n response.client_name = registrationRequest.client_name\n }\n if (registrationRequest.scope) {\n response.scope = registrationRequest.scope\n }\n\n return c.json(response, 201)\n } catch (error) {\n return c.json(\n {\n error: \"invalid_client_metadata\",\n error_description:\n \"Invalid client registration request: \" + (error instanceof Error ? error.message : String(error)),\n },\n 400,\n )\n }\n })\n\n log(\"✓ OAuth flow endpoints added\")\n}\nexport async function startServer(options: FastMCPServerOptions, transport: \"stdio\" | \"http\"): Promise<void> {\n const { server, duckpond } = createFastMCPServer(options)\n\n // Initialize DuckPond\n const initResult = await duckpond.init()\n if (!initResult.success) {\n throw new Error(`Failed to initialize DuckPond: ${initResult.error.message}`)\n }\n\n log(\"DuckPond initialized successfully\")\n\n // Start the server with appropriate transport\n if (transport === \"stdio\") {\n await server.start({\n transportType: \"stdio\",\n })\n log(\"✓ FastMCP server running with stdio transport\")\n } else {\n await server.start({\n transportType: \"httpStream\",\n httpStream: {\n port: options.port || 3000,\n endpoint: (options.endpoint || \"/mcp\") as `/${string}`,\n },\n })\n log(`✓ FastMCP server running on http://0.0.0.0:${options.port || 3000}${options.endpoint || \"/mcp\"}`)\n log(\"🔌 Connect with StreamableHTTPClientTransport\")\n }\n\n // Handle cleanup on exit\n process.on(\"SIGINT\", async () => {\n log(\"Received SIGINT, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n\n process.on(\"SIGTERM\", async () => {\n log(\"Received SIGTERM, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n}\n"],"mappings":"kKACA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,uBACxB,OAAS,cAAAC,EAAY,eAAAC,MAAmB,SACxC,OAAS,iBAAAC,MAAqB,SAI9B,UAAYC,MAAS,eACrB,OAAS,OAAAC,MAAW,MAXf,WAAW,SACd,WAAW,OAASC,GAOtB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EAAcF,EAAQ,iBAAiB,EAkBvCG,EAAMC,EAAQ,QA0BdC,EAAa,QAAQ,IAAI,qBAAuBC,EAAY,EAAE,EAAE,SAAS,KAAK,EAG9EC,EAAiB,QAAQ,IAAI,wBAC/B,SAAS,QAAQ,IAAI,wBAAyB,EAAE,EAChD,IAAM,GAAK,GAAK,GAGdC,EAAqB,IAAI,IAWzBC,EAAgB,IAAI,IAuCnB,SAASC,EAAoBC,EAGlC,CACAR,EAAI,0CAAmC,EAGvC,IAAMS,EAAW,IAAIC,EAAeF,EAAQ,MAAM,EAG5CG,EAAa,CACjB,KAAM,WACN,QAASZ,EAAY,QACrB,OAAQ,CACN,QAAS,GACT,KAAM,UACN,OAAQ,IACR,QAAS,KAAK,UAAU,CACtB,OAAQ,UACR,QAAS,sBACT,QAASA,EAAY,QACrB,UAAW,IAAI,KAAK,EAAE,YAAY,CACpC,CAAC,CACH,CACF,EAGMa,EACJJ,EAAQ,OAAO,SAAWA,EAAQ,UAC9B,IAAIK,EAAqB,CACvB,GAAGF,EACH,MAAO,CACL,QAAS,GACT,oBAAqB,CACnB,OAAQH,EAAQ,OAAO,QAAU,oBAAoBA,EAAQ,MAAQ,GAAI,GACzE,sBAAuB,GAAGA,EAAQ,OAAO,QAAU,oBAAoBA,EAAQ,MAAQ,GAAI,EAAE,mBAC7F,cAAe,GAAGA,EAAQ,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rD,2BAA4BA,EAAoB,4BAA8B,oBAChF,EAEA,OAAIA,EAAoB,cACtBG,EAAS,YAAcH,EAAoB,aAEzCA,EAAoB,QACtBG,EAAS,MAAQH,EAAoB,OAGhC5B,EAAE,KAAK+B,EAAU,GAAG,CAC7B,OAAS5C,EAAO,CACd,OAAOa,EAAE,KACP,CACE,MAAO,0BACP,kBACE,yCAA2Cb,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EACpG,EACA,GACF,CACF,CACF,CAAC,EAEDvB,EAAI,mCAA8B,CACpC,CACA,eAAsBoE,EAAY5D,EAA+B6D,EAA4C,CAC3G,GAAM,CAAE,OAAAzD,EAAQ,SAAAH,CAAS,EAAIF,EAAoBC,CAAO,EAGlD8D,EAAa,MAAM7D,EAAS,KAAK,EACvC,GAAI,CAAC6D,EAAW,QACd,MAAM,IAAI,MAAM,kCAAkCA,EAAW,MAAM,OAAO,EAAE,EAG9EtE,EAAI,mCAAmC,EAGnCqE,IAAc,SAChB,MAAMzD,EAAO,MAAM,CACjB,cAAe,OACjB,CAAC,EACDZ,EAAI,oDAA+C,IAEnD,MAAMY,EAAO,MAAM,CACjB,cAAe,aACf,WAAY,CACV,KAAMJ,EAAQ,MAAQ,IACtB,SAAWA,EAAQ,UAAY,MACjC,CACF,CAAC,EACDR,EAAI,mDAA8CQ,EAAQ,MAAQ,GAAI,GAAGA,EAAQ,UAAY,MAAM,EAAE,EACrGR,EAAI,sDAA+C,GAIrD,QAAQ,GAAG,SAAU,SAAY,CAC/BA,EAAI,oCAAoC,EACxC,MAAMS,EAAS,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,GAAG,UAAW,SAAY,CAChCT,EAAI,qCAAqC,EACzC,MAAMS,EAAS,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH","names":["webcrypto","FastMCP","createHash","randomBytes","createRequire","jwt","URL","webcrypto","require","createRequire","packageJson","log","loggers","JWT_SECRET","randomBytes","JWT_EXPIRES_IN","authorizationCodes","refreshTokens","createFastMCPServer","options","duckpond","DuckPondServer","baseConfig","server","FastMCP","request","authHeader","baseUrl","credentials","username","password","token","decoded","expectedAudience","error","querySchema","args","userId","resolveUserId","result","errorMessage","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","setupOAuthEndpoints","c","serverInfo","app","now","code","data","params","responseType","redirectUri","state","codeChallenge","codeChallengeMethod","clientId","loginForm","body","redirectUrl","URL","grantType","codeVerifier","refreshTokenParam","tokenData","accessTokenPayload","newRefreshToken","accessToken","codeData","expectedChallenge","createHash","refreshToken","registrationRequest","parseError","clientSecret","response","startServer","transport","initResult"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as
|
|
2
|
+
import{b as p}from"./chunk-RFFLXQNB.js";import"./chunk-SU42EK5H.js";import{a as D}from"./chunk-MPMUZFRC.js";import{b as i}from"./chunk-A3S6D44B.js";import{webcrypto as C}from"crypto";import{Command as U}from"commander";import{createRequire as O}from"module";globalThis.crypto||(globalThis.crypto=C);var m=O(import.meta.url),u=m("../package.json"),t=i.main;function A(){let r={memoryLimit:process.env.DUCKPOND_MEMORY_LIMIT||"4GB",threads:parseInt(process.env.DUCKPOND_THREADS||"4"),maxActiveUsers:parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS||"10"),evictionTimeout:parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT||"300000"),cacheType:process.env.DUCKPOND_CACHE_TYPE||"disk",strategy:process.env.DUCKPOND_STRATEGY||"parquet",tempDir:process.env.DUCKPOND_TEMP_DIR,cacheDir:process.env.DUCKPOND_CACHE_DIR};return process.env.DUCKPOND_R2_ACCOUNT_ID&&(r.r2={accountId:process.env.DUCKPOND_R2_ACCOUNT_ID,accessKeyId:process.env.DUCKPOND_R2_ACCESS_KEY_ID||"",secretAccessKey:process.env.DUCKPOND_R2_SECRET_ACCESS_KEY||"",bucket:process.env.DUCKPOND_R2_BUCKET||""}),process.env.DUCKPOND_S3_REGION&&(r.s3={region:process.env.DUCKPOND_S3_REGION,accessKeyId:process.env.DUCKPOND_S3_ACCESS_KEY_ID||"",secretAccessKey:process.env.DUCKPOND_S3_SECRET_ACCESS_KEY||"",bucket:process.env.DUCKPOND_S3_BUCKET||""},process.env.DUCKPOND_S3_ENDPOINT&&(r.s3.endpoint=process.env.DUCKPOND_S3_ENDPOINT)),r}var _=new U;_.name("duckpond-mcp-server").description("MCP server for multi-tenant DuckDB management with R2/S3 storage").version(u.version).option("-t, --transport <type>","Transport mode: stdio or http","stdio").option("-p, --port <port>","HTTP port (when using http transport)","3000").action(async r=>{try{let e=A(),n=D();t(`Starting DuckPond MCP Server with ${r.transport} transport`),t("Configuration:",{memoryLimit:e.memoryLimit,threads:e.threads,maxActiveUsers:e.maxActiveUsers,strategy:e.strategy,tempDir:e.tempDir,cacheDir:e.cacheDir,cacheType:e.cacheType,hasR2:!!e.r2,hasS3:!!e.s3,defaultUser:n||"(not set)"}),n&&console.error(`\u{1F464} Default user: ${n}`);let o;if(process.env.DUCKPOND_OAUTH_ENABLED==="true"){let c=process.env.DUCKPOND_OAUTH_USERNAME,a=process.env.DUCKPOND_OAUTH_PASSWORD;(!c||!a)&&(console.error("\u274C OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required"),process.exit(1)),o={enabled:!0,username:c,password:a,userId:process.env.DUCKPOND_OAUTH_USER_ID||c,email:process.env.DUCKPOND_OAUTH_EMAIL,issuer:process.env.DUCKPOND_OAUTH_ISSUER||`http://localhost:${parseInt(r.port)||3e3}`,resource:process.env.DUCKPOND_OAUTH_RESOURCE},console.error("\u{1F510} OAuth enabled with username/password authentication"),console.error(` Username: ${o.username}`),console.error(` User ID: ${o.userId}`),console.error(" \u2713 Login form will be shown at authorization endpoint")}let s;process.env.DUCKPOND_BASIC_AUTH_USERNAME&&process.env.DUCKPOND_BASIC_AUTH_PASSWORD&&(s={username:process.env.DUCKPOND_BASIC_AUTH_USERNAME,password:process.env.DUCKPOND_BASIC_AUTH_PASSWORD,userId:process.env.DUCKPOND_BASIC_AUTH_USER_ID,email:process.env.DUCKPOND_BASIC_AUTH_EMAIL},console.error("\u{1F510} Basic authentication enabled"),console.error(` Username: ${s.username}`),console.error(` User ID: ${s.userId||s.username}`)),r.transport==="stdio"||r.transport==="http"?await p({config:e,port:parseInt(r.port)||3e3,endpoint:"/mcp",oauth:o,basicAuth:s},r.transport==="stdio"?"stdio":"http"):(t(`Unknown transport: ${r.transport}`),process.exit(1))}catch(e){t("Fatal error:",e),console.error("Fatal error:",e),process.exit(1)}});_.parse();
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { Command } from \"commander\"\nimport { createRequire } from \"module\"\n\nimport type { OAuthConfig } from \"./server\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport { startServer } from \"./server\"\nimport type { DuckPondServerConfig } from \"./server-core\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.main\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n const config: DuckPondServerConfig = {\n memoryLimit: process.env.DUCKPOND_MEMORY_LIMIT || \"4GB\",\n threads: parseInt(process.env.DUCKPOND_THREADS || \"4\"),\n maxActiveUsers: parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS || \"10\"),\n evictionTimeout: parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT || \"300000\"),\n cacheType: (process.env.DUCKPOND_CACHE_TYPE as \"disk\" | \"memory\" | \"noop\") || \"disk\",\n strategy: (process.env.DUCKPOND_STRATEGY as \"parquet\" | \"duckdb\" | \"hybrid\") || \"parquet\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR,\n }\n\n // R2 configuration\n if (process.env.DUCKPOND_R2_ACCOUNT_ID) {\n config.r2 = {\n accountId: process.env.DUCKPOND_R2_ACCOUNT_ID,\n accessKeyId: process.env.DUCKPOND_R2_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_R2_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_R2_BUCKET || \"\",\n }\n }\n\n // S3 configuration\n if (process.env.DUCKPOND_S3_REGION) {\n config.s3 = {\n region: process.env.DUCKPOND_S3_REGION,\n accessKeyId: process.env.DUCKPOND_S3_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_S3_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_S3_BUCKET || \"\",\n }\n\n if (process.env.DUCKPOND_S3_ENDPOINT) {\n config.s3.endpoint = process.env.DUCKPOND_S3_ENDPOINT\n }\n }\n\n return config\n}\n\n/**\n * Main CLI program\n */\nconst program = new Command()\n\nprogram\n .name(\"duckpond-mcp-server\")\n .description(\"MCP server for multi-tenant DuckDB management with R2/S3 storage\")\n .version(packageJson.version)\n .option(\"-t, --transport <type>\", \"Transport mode: stdio or http\", \"stdio\")\n .option(\"-p, --port <port>\", \"HTTP port (when using http transport)\", \"3000\")\n .action(async (options) => {\n try {\n const config = getConfigFromEnv()\n\n log(`Starting DuckPond MCP Server with ${options.transport} transport`)\n log(\"Configuration:\", {\n memoryLimit: config.memoryLimit,\n threads: config.threads,\n maxActiveUsers: config.maxActiveUsers,\n strategy: config.strategy,\n tempDir: config.tempDir,\n cacheDir: config.cacheDir,\n cacheType: config.cacheType,\n hasR2: !!config.r2,\n hasS3: !!config.s3,\n })\n\n // Load OAuth configuration from environment variables (for HTTP transport)\n let oauthConfig: OAuthConfig | undefined\n if (process.env.DUCKPOND_OAUTH_ENABLED === \"true\") {\n const username = process.env.DUCKPOND_OAUTH_USERNAME\n const password = process.env.DUCKPOND_OAUTH_PASSWORD\n\n if (!username || !password) {\n console.error(\"❌ OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required\")\n process.exit(1)\n }\n\n oauthConfig = {\n enabled: true,\n username,\n password,\n userId: process.env.DUCKPOND_OAUTH_USER_ID || username,\n email: process.env.DUCKPOND_OAUTH_EMAIL,\n issuer: process.env.DUCKPOND_OAUTH_ISSUER || `http://localhost:${parseInt(options.port) || 3000}`,\n resource: process.env.DUCKPOND_OAUTH_RESOURCE,\n }\n\n console.error(\"🔐 OAuth enabled with username/password authentication\")\n console.error(` Username: ${oauthConfig.username}`)\n console.error(` User ID: ${oauthConfig.userId}`)\n console.error(\" ✓ Login form will be shown at authorization endpoint\")\n }\n\n // Load Basic Auth configuration from environment variables (for HTTP transport)\n let basicAuthConfig: { username: string; password: string; userId?: string; email?: string } | undefined\n if (process.env.DUCKPOND_BASIC_AUTH_USERNAME && process.env.DUCKPOND_BASIC_AUTH_PASSWORD) {\n basicAuthConfig = {\n username: process.env.DUCKPOND_BASIC_AUTH_USERNAME,\n password: process.env.DUCKPOND_BASIC_AUTH_PASSWORD,\n userId: process.env.DUCKPOND_BASIC_AUTH_USER_ID,\n email: process.env.DUCKPOND_BASIC_AUTH_EMAIL,\n }\n\n console.error(\"🔐 Basic authentication enabled\")\n console.error(` Username: ${basicAuthConfig.username}`)\n console.error(` User ID: ${basicAuthConfig.userId || basicAuthConfig.username}`)\n }\n\n // Start unified FastMCP server with appropriate transport\n if (options.transport === \"stdio\" || options.transport === \"http\") {\n await startServer(\n {\n config,\n port: parseInt(options.port) || 3000,\n endpoint: \"/mcp\",\n oauth: oauthConfig,\n basicAuth: basicAuthConfig,\n },\n options.transport === \"stdio\" ? \"stdio\" : \"http\",\n )\n } else {\n log(`Unknown transport: ${options.transport}`)\n process.exit(1)\n }\n } catch (error) {\n log(\"Fatal error:\", error)\n console.error(\"Fatal error:\", error)\n process.exit(1)\n }\n })\n\nprogram.parse()\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { Command } from \"commander\"\nimport { createRequire } from \"module\"\n\nimport type { OAuthConfig } from \"./server\"\nimport { getDefaultUserId } from \"./tools\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport { startServer } from \"./server\"\nimport type { DuckPondServerConfig } from \"./server-core\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.main\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n const config: DuckPondServerConfig = {\n memoryLimit: process.env.DUCKPOND_MEMORY_LIMIT || \"4GB\",\n threads: parseInt(process.env.DUCKPOND_THREADS || \"4\"),\n maxActiveUsers: parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS || \"10\"),\n evictionTimeout: parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT || \"300000\"),\n cacheType: (process.env.DUCKPOND_CACHE_TYPE as \"disk\" | \"memory\" | \"noop\") || \"disk\",\n strategy: (process.env.DUCKPOND_STRATEGY as \"parquet\" | \"duckdb\" | \"hybrid\") || \"parquet\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR,\n }\n\n // R2 configuration\n if (process.env.DUCKPOND_R2_ACCOUNT_ID) {\n config.r2 = {\n accountId: process.env.DUCKPOND_R2_ACCOUNT_ID,\n accessKeyId: process.env.DUCKPOND_R2_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_R2_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_R2_BUCKET || \"\",\n }\n }\n\n // S3 configuration\n if (process.env.DUCKPOND_S3_REGION) {\n config.s3 = {\n region: process.env.DUCKPOND_S3_REGION,\n accessKeyId: process.env.DUCKPOND_S3_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_S3_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_S3_BUCKET || \"\",\n }\n\n if (process.env.DUCKPOND_S3_ENDPOINT) {\n config.s3.endpoint = process.env.DUCKPOND_S3_ENDPOINT\n }\n }\n\n return config\n}\n\n/**\n * Main CLI program\n */\nconst program = new Command()\n\nprogram\n .name(\"duckpond-mcp-server\")\n .description(\"MCP server for multi-tenant DuckDB management with R2/S3 storage\")\n .version(packageJson.version)\n .option(\"-t, --transport <type>\", \"Transport mode: stdio or http\", \"stdio\")\n .option(\"-p, --port <port>\", \"HTTP port (when using http transport)\", \"3000\")\n .action(async (options) => {\n try {\n const config = getConfigFromEnv()\n\n const defaultUser = getDefaultUserId()\n log(`Starting DuckPond MCP Server with ${options.transport} transport`)\n log(\"Configuration:\", {\n memoryLimit: config.memoryLimit,\n threads: config.threads,\n maxActiveUsers: config.maxActiveUsers,\n strategy: config.strategy,\n tempDir: config.tempDir,\n cacheDir: config.cacheDir,\n cacheType: config.cacheType,\n hasR2: !!config.r2,\n hasS3: !!config.s3,\n defaultUser: defaultUser || \"(not set)\",\n })\n\n if (defaultUser) {\n console.error(`👤 Default user: ${defaultUser}`)\n }\n\n // Load OAuth configuration from environment variables (for HTTP transport)\n let oauthConfig: OAuthConfig | undefined\n if (process.env.DUCKPOND_OAUTH_ENABLED === \"true\") {\n const username = process.env.DUCKPOND_OAUTH_USERNAME\n const password = process.env.DUCKPOND_OAUTH_PASSWORD\n\n if (!username || !password) {\n console.error(\"❌ OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required\")\n process.exit(1)\n }\n\n oauthConfig = {\n enabled: true,\n username,\n password,\n userId: process.env.DUCKPOND_OAUTH_USER_ID || username,\n email: process.env.DUCKPOND_OAUTH_EMAIL,\n issuer: process.env.DUCKPOND_OAUTH_ISSUER || `http://localhost:${parseInt(options.port) || 3000}`,\n resource: process.env.DUCKPOND_OAUTH_RESOURCE,\n }\n\n console.error(\"🔐 OAuth enabled with username/password authentication\")\n console.error(` Username: ${oauthConfig.username}`)\n console.error(` User ID: ${oauthConfig.userId}`)\n console.error(\" ✓ Login form will be shown at authorization endpoint\")\n }\n\n // Load Basic Auth configuration from environment variables (for HTTP transport)\n let basicAuthConfig: { username: string; password: string; userId?: string; email?: string } | undefined\n if (process.env.DUCKPOND_BASIC_AUTH_USERNAME && process.env.DUCKPOND_BASIC_AUTH_PASSWORD) {\n basicAuthConfig = {\n username: process.env.DUCKPOND_BASIC_AUTH_USERNAME,\n password: process.env.DUCKPOND_BASIC_AUTH_PASSWORD,\n userId: process.env.DUCKPOND_BASIC_AUTH_USER_ID,\n email: process.env.DUCKPOND_BASIC_AUTH_EMAIL,\n }\n\n console.error(\"🔐 Basic authentication enabled\")\n console.error(` Username: ${basicAuthConfig.username}`)\n console.error(` User ID: ${basicAuthConfig.userId || basicAuthConfig.username}`)\n }\n\n // Start unified FastMCP server with appropriate transport\n if (options.transport === \"stdio\" || options.transport === \"http\") {\n await startServer(\n {\n config,\n port: parseInt(options.port) || 3000,\n endpoint: \"/mcp\",\n oauth: oauthConfig,\n basicAuth: basicAuthConfig,\n },\n options.transport === \"stdio\" ? \"stdio\" : \"http\",\n )\n } else {\n log(`Unknown transport: ${options.transport}`)\n process.exit(1)\n }\n } catch (error) {\n log(\"Fatal error:\", error)\n console.error(\"Fatal error:\", error)\n process.exit(1)\n }\n })\n\nprogram.parse()\n"],"mappings":";oJAGA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,YACxB,OAAS,iBAAAC,MAAqB,SALzB,WAAW,SACd,WAAW,OAASC,GAStB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EA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ACAN,EAAQ,YAAc,QAAU,QAAU,MAC5C,GAEAN,EAAI,sBAAsBM,EAAQ,SAAS,EAAE,EAC7C,QAAQ,KAAK,CAAC,EAElB,OAASQ,EAAO,CACdd,EAAI,eAAgBc,CAAK,EACzB,QAAQ,MAAM,eAAgBA,CAAK,EACnC,QAAQ,KAAK,CAAC,CAChB,CACF,CAAC,EAEHV,EAAQ,MAAM","names":["webcrypto","Command","createRequire","webcrypto","require","createRequire","packageJson","log","loggers","getConfigFromEnv","config","program","Command","options","defaultUser","getDefaultUserId","oauthConfig","username","password","basicAuthConfig","startServer","error"]}
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-RFFLXQNB.js";import"./chunk-SU42EK5H.js";import"./chunk-MPMUZFRC.js";import"./chunk-A3S6D44B.js";export{a as createFastMCPServer,b as startServer};
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -2,61 +2,70 @@ import { z } from 'zod';
|
|
|
2
2
|
import { DuckPondServer } from '../server-core.js';
|
|
3
3
|
import 'duckpond';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Get the default user ID from environment variable
|
|
7
|
+
*/
|
|
8
|
+
declare function getDefaultUserId(): string | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Resolve user ID from input or default
|
|
11
|
+
* @throws Error if no user ID is available
|
|
12
|
+
*/
|
|
13
|
+
declare function resolveUserId(inputUserId?: string): string;
|
|
5
14
|
/**
|
|
6
15
|
* Zod schema for query tool
|
|
7
16
|
*/
|
|
8
17
|
declare const querySchema: z.ZodObject<{
|
|
9
|
-
userId: z.ZodString
|
|
18
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
10
19
|
sql: z.ZodString;
|
|
11
20
|
}, "strip", z.ZodTypeAny, {
|
|
12
|
-
userId: string;
|
|
13
21
|
sql: string;
|
|
22
|
+
userId?: string | undefined;
|
|
14
23
|
}, {
|
|
15
|
-
userId: string;
|
|
16
24
|
sql: string;
|
|
25
|
+
userId?: string | undefined;
|
|
17
26
|
}>;
|
|
18
27
|
/**
|
|
19
28
|
* Zod schema for execute tool
|
|
20
29
|
*/
|
|
21
30
|
declare const executeSchema: z.ZodObject<{
|
|
22
|
-
userId: z.ZodString
|
|
31
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
23
32
|
sql: z.ZodString;
|
|
24
33
|
}, "strip", z.ZodTypeAny, {
|
|
25
|
-
userId: string;
|
|
26
34
|
sql: string;
|
|
35
|
+
userId?: string | undefined;
|
|
27
36
|
}, {
|
|
28
|
-
userId: string;
|
|
29
37
|
sql: string;
|
|
38
|
+
userId?: string | undefined;
|
|
30
39
|
}>;
|
|
31
40
|
/**
|
|
32
41
|
* Zod schema for getUserStats tool
|
|
33
42
|
*/
|
|
34
43
|
declare const getUserStatsSchema: z.ZodObject<{
|
|
35
|
-
userId: z.ZodString
|
|
44
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
36
45
|
}, "strip", z.ZodTypeAny, {
|
|
37
|
-
userId
|
|
46
|
+
userId?: string | undefined;
|
|
38
47
|
}, {
|
|
39
|
-
userId
|
|
48
|
+
userId?: string | undefined;
|
|
40
49
|
}>;
|
|
41
50
|
/**
|
|
42
51
|
* Zod schema for isAttached tool
|
|
43
52
|
*/
|
|
44
53
|
declare const isAttachedSchema: z.ZodObject<{
|
|
45
|
-
userId: z.ZodString
|
|
54
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
46
55
|
}, "strip", z.ZodTypeAny, {
|
|
47
|
-
userId
|
|
56
|
+
userId?: string | undefined;
|
|
48
57
|
}, {
|
|
49
|
-
userId
|
|
58
|
+
userId?: string | undefined;
|
|
50
59
|
}>;
|
|
51
60
|
/**
|
|
52
61
|
* Zod schema for detachUser tool
|
|
53
62
|
*/
|
|
54
63
|
declare const detachUserSchema: z.ZodObject<{
|
|
55
|
-
userId: z.ZodString
|
|
64
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
56
65
|
}, "strip", z.ZodTypeAny, {
|
|
57
|
-
userId
|
|
66
|
+
userId?: string | undefined;
|
|
58
67
|
}, {
|
|
59
|
-
userId
|
|
68
|
+
userId?: string | undefined;
|
|
60
69
|
}>;
|
|
61
70
|
/**
|
|
62
71
|
* Zod schema for listUsers tool
|
|
@@ -122,4 +131,4 @@ declare const tools: {
|
|
|
122
131
|
};
|
|
123
132
|
};
|
|
124
133
|
|
|
125
|
-
export { detachUserSchema, executeSchema, getUserStatsSchema, isAttachedSchema, listUsersSchema, querySchema, tools };
|
|
134
|
+
export { detachUserSchema, executeSchema, getDefaultUserId, getUserStatsSchema, isAttachedSchema, listUsersSchema, querySchema, resolveUserId, tools };
|
package/dist/tools/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i}from"../chunk-MPMUZFRC.js";import"../chunk-A3S6D44B.js";export{g as detachUserSchema,d as executeSchema,a as getDefaultUserId,e as getUserStatsSchema,f as isAttachedSchema,h as listUsersSchema,c as querySchema,b as resolveUserId,i as tools};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
package/dist/chunk-43NWQIU3.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as o}from"./chunk-A3S6D44B.js";import{z as r}from"zod";var c=o.tools,u=r.object({userId:r.string().min(1).describe("User identifier"),sql:r.string().min(1).describe("SQL query to execute")}),a=r.object({userId:r.string().min(1).describe("User identifier"),sql:r.string().min(1).describe("SQL statement to execute (DDL/DML)")}),d=r.object({userId:r.string().min(1).describe("User identifier")}),l=r.object({userId:r.string().min(1).describe("User identifier")}),f=r.object({userId:r.string().min(1).describe("User identifier")}),m=r.object({}),S={async query(s,t){c(`Tool: query for user ${t.userId}`);let e=await s.query(t.userId,t.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2)}]}},async execute(s,t){c(`Tool: execute for user ${t.userId}`);let e=await s.execute(t.userId,t.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2)}]}},async getUserStats(s,t){c(`Tool: getUserStats for user ${t.userId}`);let e=await s.getUserStats(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2)}]}},isAttached(s,t){c(`Tool: isAttached for user ${t.userId}`);let e=s.isAttached(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({attached:e.data,userId:t.userId},null,2)}]}},async detachUser(s,t){c(`Tool: detachUser for user ${t.userId}`);let e=await s.detachUser(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:`User ${t.userId} detached successfully`},null,2)}]}},listUsers(s,t){c("Tool: listUsers");let e=s.listUsers();if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify(e.data,null,2)}]}}};export{u as a,a as b,d as c,l as d,f as e,m as f,S as g};
|
|
2
|
-
//# sourceMappingURL=chunk-43NWQIU3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\nimport type { DuckPondServer } from \"../server-core\"\nimport { loggers } from \"../utils/logger\"\n\nconst log = loggers.tools\n\n/**\n * Zod schema for query tool\n */\nexport const querySchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n sql: z.string().min(1).describe(\"SQL query to execute\"),\n})\n\n/**\n * Zod schema for execute tool\n */\nexport const executeSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n sql: z.string().min(1).describe(\"SQL statement to execute (DDL/DML)\"),\n})\n\n/**\n * Zod schema for getUserStats tool\n */\nexport const getUserStatsSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for isAttached tool\n */\nexport const isAttachedSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for detachUser tool\n */\nexport const detachUserSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for listUsers tool\n */\nexport const listUsersSchema = z.object({})\n\n/**\n * Tool implementations for MCP server\n */\nexport const tools = {\n /**\n * Execute a SQL query for a user\n */\n async query(server: DuckPondServer, input: z.infer<typeof querySchema>) {\n log(`Tool: query for user ${input.userId}`)\n const result = await server.query(input.userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Execute DDL/DML statement\n */\n async execute(server: DuckPondServer, input: z.infer<typeof executeSchema>) {\n log(`Tool: execute for user ${input.userId}`)\n const result = await server.execute(input.userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Get user database statistics\n */\n async getUserStats(server: DuckPondServer, input: z.infer<typeof getUserStatsSchema>) {\n log(`Tool: getUserStats for user ${input.userId}`)\n const result = await server.getUserStats(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Check if user is attached\n */\n isAttached(server: DuckPondServer, input: z.infer<typeof isAttachedSchema>) {\n log(`Tool: isAttached for user ${input.userId}`)\n const result = server.isAttached(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n attached: result.data,\n userId: input.userId,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Detach a user from cache\n */\n async detachUser(server: DuckPondServer, input: z.infer<typeof detachUserSchema>) {\n log(`Tool: detachUser for user ${input.userId}`)\n const result = await server.detachUser(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: `User ${input.userId} detached successfully`,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * List all currently cached users\n */\n listUsers(server: DuckPondServer, _input: z.infer<typeof listUsersSchema>) {\n log(\"Tool: listUsers\")\n const result = server.listUsers()\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n }\n },\n}\n"],"mappings":"wCAAA,OAAS,KAAAA,MAAS,MAKlB,IAAMC,EAAMC,EAAQ,MAKPC,EAAcC,EAAE,OAAO,CAClC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,EACpD,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,sBAAsB,CACxD,CAAC,EAKYC,EAAgBD,EAAE,OAAO,CACpC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,EACpD,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,oCAAoC,CACtE,CAAC,EAKYE,EAAqBF,EAAE,OAAO,CACzC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,CACtD,CAAC,EAKYG,EAAmBH,EAAE,OAAO,CACvC,OAAQA,EAAE,OAAO,E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AAW,YAAY,CACjD,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,WAAWF,EAAwBC,EAAyC,CAC1EX,EAAI,6BAA6BW,EAAM,MAAM,EAAE,EAC/C,IAAMC,EAASF,EAAO,WAAWC,EAAM,MAAM,EAE7C,GAAI,CAACC,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,SAAUA,EAAO,KACjB,OAAQD,EAAM,MAChB,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,MAAM,WAAWD,EAAwBC,EAAyC,CAChFX,EAAI,6BAA6BW,EAAM,MAAM,EAAE,EAC/C,IAAMC,EAAS,MAAMF,EAAO,WAAWC,EAAM,MAAM,EAEnD,GAAI,CAACC,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,QAAS,GACT,QAAS,QAAQD,EAAM,MAAM,wBAC/B,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,UAAUD,EAAwBG,EAAyC,CACzEb,EAAI,iBAAiB,EACrB,IAAMY,EAASF,EAAO,UAAU,EAEhC,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UAAUA,EAAO,KAAM,KAAM,CAAC,CAC3C,CACF,CACF,CACF,CACF","names":["z","log","loggers","querySchema","z","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","tools","server","input","result","_input"]}
|
package/dist/chunk-TAP5LWZ7.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import{a as C}from"./chunk-SU42EK5H.js";import{a as O,b as T,c as $,d as A,e as I,f as P}from"./chunk-43NWQIU3.js";import{b as R}from"./chunk-A3S6D44B.js";import{webcrypto as z}from"crypto";import{FastMCP as E}from"@jordanburke/fastmcp";import{createHash as D,randomBytes as f}from"crypto";import{createRequire as j}from"module";import*as y from"jsonwebtoken";import{URL as N}from"url";globalThis.crypto||(globalThis.crypto=z);var q=j(import.meta.url),v=q("../package.json"),u=R.fastmcp,b=process.env.DUCKPOND_JWT_SECRET||f(32).toString("hex"),S=process.env.DUCKPOND_JWT_EXPIRES_IN?parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN,10):365*24*60*60,_=new Map,m=new Map;function J(t){u("\u{1F680} Initializing FastMCP server...");let i=new C(t.config),h={name:"duckpond",version:v.version,health:{enabled:!0,path:"/health",status:200,message:JSON.stringify({status:"healthy",service:"duckpond-mcp-server",version:v.version,timestamp:new Date().toISOString()})}},s=t.oauth?.enabled||t.basicAuth?new E({...h,oauth:{enabled:!0,authorizationServer:{issuer:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,authorizationEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/authorize`,tokenEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/token`,jwksUri:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/jwks`,registrationEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/register`,responseTypesSupported:["code"],grantTypesSupported:["authorization_code"],tokenEndpointAuthMethodsSupported:["client_secret_post","client_secret_basic"],codeChallengeMethodsSupported:["S256","plain"]},protectedResource:{resource:process.env.DUCKPOND_OAUTH_RESOURCE||t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`,authorizationServers:[t.oauth?.issuer||`http://localhost:${t.port||3e3}`]}},authenticate:r=>{let e=r.headers?.authorization,n=t.oauth?.issuer||`http://localhost:${t.port||3e3}`;if(!e)throw t.oauth?.enabled?new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required. Please authenticate via OAuth."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${n}/oauth/authorize", resource="${n}/.well-known/oauth-protected-resource"`}}):new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json"}});if(t.basicAuth&&e.startsWith("Basic ")){let c=Buffer.from(e.slice(6),"base64").toString("utf-8"),[a,d]=c.split(":");if(a===t.basicAuth.username&&d===t.basicAuth.password)return Promise.resolve({userId:t.basicAuth.userId||a,email:t.basicAuth.email||`${a}@example.com`,scope:"read write"});throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid username or password"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Basic realm="MCP"'}})}if(t.oauth?.enabled&&e.startsWith("Bearer ")){let c=e.slice(7);try{let a=y.verify(c,b);if(!a.sub||!a.iat||!a.exp)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid token structure"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid token structure"'}});let d=t.oauth?.resource||`${n}/mcp`;if(a.aud&&a.aud!==d)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Token audience mismatch"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Token audience mismatch"'}});return Promise.resolve({userId:a.sub,email:a.email||"",scope:a.scope||"read write"})}catch(a){throw a instanceof Response?a:new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid or expired token"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid or expired token"'}})}}throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid authorization header format"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${n}/oauth/authorize", resource="${n}/.well-known/oauth-protected-resource"`}})}}):new E(h);return s.addTool({name:"query",description:"Execute a SQL query for a specific user and return results",parameters:O,execute:async r=>{try{let e=await i.query(r.userId,r.sql);return e.success?JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in query tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"execute",description:"Execute SQL statement (DDL/DML) for a specific user without returning results",parameters:T,execute:async r=>{try{let e=await i.execute(r.userId,r.sql);return e.success?JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in execute tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"getUserStats",description:"Get statistics about a user's database (memory usage, query count, etc.)",parameters:$,execute:async r=>{try{let e=await i.getUserStats(r.userId);return e.success?JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in getUserStats tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"isAttached",description:"Check if a user's database is currently cached in memory",parameters:A,execute:async r=>{try{let e=i.isAttached(r.userId);return e.success?JSON.stringify({attached:e.data,userId:r.userId},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in isAttached tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"detachUser",description:"Manually detach a user's database from the cache to free resources",parameters:I,execute:async r=>{try{let e=await i.detachUser(r.userId);return e.success?JSON.stringify({success:!0,message:`User ${r.userId} detached successfully`},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in detachUser tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"listUsers",description:"List all currently cached users and cache statistics",parameters:P,execute:async()=>{try{let r=i.listUsers();return r.success?JSON.stringify(r.data,null,2):`ERROR: ${r.error.message}`}catch(r){u("Error in listUsers tool:",r);let e=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:e},null,2)}`}}}),t.oauth?.enabled&&W(s,t),s.getApp().get("/",r=>{let e=t.oauth?.issuer||`http://localhost:${t.port||3e3}`,n={name:"DuckPond MCP Server",version:v.version,description:"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage",service:"duckpond-mcp-server",capabilities:{tools:["query","execute","getUserStats","isAttached","detachUser","listUsers"],transports:["stdio","http"],authentication:{oauth:t.oauth?.enabled||!1,basicAuth:!!t.basicAuth}},endpoints:{mcp:`${e}${t.endpoint||"/mcp"}`,health:`${e}/health`,...t.oauth?.enabled&&{oauth:{authorization:`${e}/oauth/authorize`,token:`${e}/oauth/token`,jwks:`${e}/oauth/jwks`,register:`${e}/oauth/register`}}},timestamp:new Date().toISOString()};return r.json(n)}),u("\u2713 FastMCP server created"),{server:s,duckpond:i}}function W(t,i){let h=t.getApp();setInterval(()=>{let s=Date.now();for(let[o,r]of _.entries())s-r.createdAt>6e5&&_.delete(o);for(let[o,r]of m.entries())s-r.createdAt>2592e6&&m.delete(o)},6e4),h.get("/oauth/authorize",s=>{let o=s.req.query(),r=o.response_type,e=o.redirect_uri,n=o.state,c=o.code_challenge,a=o.code_challenge_method,d=o.client_id;if(r!=="code")return s.json({error:"unsupported_response_type",error_description:"Only 'code' response type is supported"},400);if(!e)return s.json({error:"invalid_request",error_description:"redirect_uri is required"},400);if(c&&(!a||!["S256","plain"].includes(a)))return s.json({error:"invalid_request",error_description:"Invalid code_challenge_method. Only 'S256' and 'plain' are supported"},400);let l=`
|
|
2
|
-
<!DOCTYPE html>
|
|
3
|
-
<html>
|
|
4
|
-
<head>
|
|
5
|
-
<title>OAuth Login - DuckPond MCP Server</title>
|
|
6
|
-
<style>
|
|
7
|
-
body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }
|
|
8
|
-
.form-group { margin-bottom: 15px; }
|
|
9
|
-
label { display: block; margin-bottom: 5px; font-weight: bold; }
|
|
10
|
-
input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
|
|
11
|
-
button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
|
|
12
|
-
button:hover { background: #005a87; }
|
|
13
|
-
.app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }
|
|
14
|
-
</style>
|
|
15
|
-
</head>
|
|
16
|
-
<body>
|
|
17
|
-
<div class="app-info">
|
|
18
|
-
<h3>\u{1F510} OAuth Authorization</h3>
|
|
19
|
-
<p><strong>Application:</strong> ${d||"MCP Client"}</p>
|
|
20
|
-
<p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>
|
|
21
|
-
</div>
|
|
22
|
-
|
|
23
|
-
<form method="POST" action="/oauth/authorize">
|
|
24
|
-
<input type="hidden" name="response_type" value="${r}">
|
|
25
|
-
<input type="hidden" name="redirect_uri" value="${e}">
|
|
26
|
-
<input type="hidden" name="state" value="${n||""}">
|
|
27
|
-
<input type="hidden" name="code_challenge" value="${c||""}">
|
|
28
|
-
<input type="hidden" name="code_challenge_method" value="${a||""}">
|
|
29
|
-
<input type="hidden" name="client_id" value="${d||""}">
|
|
30
|
-
|
|
31
|
-
<div class="form-group">
|
|
32
|
-
<label for="username">Username:</label>
|
|
33
|
-
<input type="text" id="username" name="username" required>
|
|
34
|
-
</div>
|
|
35
|
-
|
|
36
|
-
<div class="form-group">
|
|
37
|
-
<label for="password">Password:</label>
|
|
38
|
-
<input type="password" id="password" name="password" required>
|
|
39
|
-
</div>
|
|
40
|
-
|
|
41
|
-
<button type="submit">Authorize Application</button>
|
|
42
|
-
</form>
|
|
43
|
-
</body>
|
|
44
|
-
</html>`;return s.html(l)}),h.post("/oauth/authorize",async s=>{try{let o=await s.req.text(),r=new URLSearchParams(o),e=r.get("username"),n=r.get("password"),c=r.get("redirect_uri"),a=r.get("state"),d=r.get("code_challenge"),l=r.get("code_challenge_method");if(e!==i.oauth?.username||n!==i.oauth?.password)return s.html(`
|
|
45
|
-
<!DOCTYPE html>
|
|
46
|
-
<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>
|
|
47
|
-
<body><div class="error">\u274C Invalid username or password</div><a href="javascript:history.back()">\u2190 Try Again</a></body></html>`,401);let w=f(16).toString("hex");_.set(w,{createdAt:Date.now(),redirectUri:c||"",codeChallenge:d||void 0,codeChallengeMethod:l||void 0,userId:i.oauth?.userId||e||"oauth-user"});let g=new N(c||"");return g.searchParams.set("code",w),a&&g.searchParams.set("state",a),s.redirect(g.toString(),302)}catch{return s.json({error:"invalid_request",error_description:"Failed to process authorization request"},400)}}),h.post("/oauth/token",async s=>{let o=await s.req.text(),r=new URLSearchParams(o),e=r.get("grant_type"),n=r.get("code"),c=r.get("redirect_uri"),a=r.get("code_verifier"),d=r.get("refresh_token");if(e==="refresh_token"){if(!d)return s.json({error:"invalid_request",error_description:"refresh_token is required for refresh_token grant type"},400);let p=m.get(d);if(!p)return s.json({error:"invalid_grant",error_description:"Invalid or expired refresh token"},400);m.delete(d);let M={sub:p.userId,email:p.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+S,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},x=f(32).toString("hex");m.set(x,{createdAt:Date.now(),userId:p.userId,email:p.email});let U=y.sign(M,b);return s.json({access_token:U,token_type:"Bearer",expires_in:S,scope:"read write",refresh_token:x})}if(e!=="authorization_code")return s.json({error:"unsupported_grant_type",error_description:"Only 'authorization_code' and 'refresh_token' grant types are supported"},400);let l=_.get(n||"");if(!l)return s.json({error:"invalid_grant",error_description:"Invalid or expired authorization code"},400);if(l.redirectUri&&l.redirectUri!==c)return s.json({error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(l.codeChallenge){if(!a)return s.json({error:"invalid_grant",error_description:"code_verifier is required when code_challenge was used"},400);let p;if(l.codeChallengeMethod==="S256"?p=D("sha256").update(a).digest().toString("base64url"):p=a,p!==l.codeChallenge)return s.json({error:"invalid_grant",error_description:"Invalid code_verifier"},400)}_.delete(n);let w={sub:l.userId,email:i.oauth?.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+S,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},g=f(32).toString("hex");m.set(g,{createdAt:Date.now(),userId:l.userId,email:i.oauth?.email});let k=y.sign(w,b);return s.json({access_token:k,token_type:"Bearer",expires_in:S,scope:"read write",refresh_token:g})}),h.get("/oauth/jwks",s=>s.json({keys:[{kty:"oct",use:"sig",kid:"duckpond-hmac-key",alg:"HS256"}]})),h.post("/oauth/register",async s=>{try{let o={};try{let c=await s.req.text();if(c&&c!=="[object Object]")try{o=JSON.parse(c)}catch{o=Object.fromEntries(new URLSearchParams(c))}}catch(c){u("Error parsing request body:",c)}let r=`client-${f(8).toString("hex")}`,e=f(16).toString("hex"),n={client_id:r,client_secret:e,client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:o.grant_types||["authorization_code"],response_types:o.response_types||["code"],redirect_uris:o.redirect_uris||[],token_endpoint_auth_method:o.token_endpoint_auth_method||"client_secret_post"};return o.client_name&&(n.client_name=o.client_name),o.scope&&(n.scope=o.scope),s.json(n,201)}catch(o){return s.json({error:"invalid_client_metadata",error_description:"Invalid client registration request: "+(o instanceof Error?o.message:String(o))},400)}}),u("\u2713 OAuth flow endpoints added")}async function Y(t,i){let{server:h,duckpond:s}=J(t),o=await s.init();if(!o.success)throw new Error(`Failed to initialize DuckPond: ${o.error.message}`);u("DuckPond initialized successfully"),i==="stdio"?(await h.start({transportType:"stdio"}),u("\u2713 FastMCP server running with stdio transport")):(await h.start({transportType:"httpStream",httpStream:{port:t.port||3e3,endpoint:t.endpoint||"/mcp"}}),u(`\u2713 FastMCP server running on http://0.0.0.0:${t.port||3e3}${t.endpoint||"/mcp"}`),u("\u{1F50C} Connect with StreamableHTTPClientTransport")),process.on("SIGINT",async()=>{u("Received SIGINT, closing server..."),await s.close(),process.exit(0)}),process.on("SIGTERM",async()=>{u("Received SIGTERM, closing server..."),await s.close(),process.exit(0)})}export{J as a,Y as b};
|
|
48
|
-
//# sourceMappingURL=chunk-TAP5LWZ7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { FastMCP } from \"@jordanburke/fastmcp\"\nimport { createHash, randomBytes } from \"crypto\"\nimport { createRequire } from \"module\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport * as jwt from \"jsonwebtoken\"\nimport { URL } from \"url\"\nimport { z } from \"zod\"\n\nimport { DuckPondServer, type DuckPondServerConfig } from \"./server-core\"\nimport {\n detachUserSchema,\n executeSchema,\n getUserStatsSchema,\n isAttachedSchema,\n listUsersSchema,\n querySchema,\n} from \"./tools\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.fastmcp\n\nexport type OAuthConfig = {\n enabled: boolean\n username: string\n password: string\n userId: string\n email?: string\n issuer?: string\n resource?: string\n}\n\nexport type FastMCPServerOptions = {\n config: DuckPondServerConfig\n port?: number\n endpoint?: string\n oauth?: OAuthConfig\n basicAuth?: {\n username: string\n password: string\n userId?: string\n email?: string\n }\n}\n\n// JWT secret for token signing/validation\nconst JWT_SECRET = process.env.DUCKPOND_JWT_SECRET || randomBytes(32).toString(\"hex\")\n\n// JWT token expiration configuration (default: 1 year)\nconst JWT_EXPIRES_IN = process.env.DUCKPOND_JWT_EXPIRES_IN\n ? parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN, 10)\n : 365 * 24 * 60 * 60 // 1 year in seconds\n\n// In-memory stores for OAuth flow\nconst authorizationCodes = new Map<\n string,\n {\n createdAt: number\n redirectUri?: string\n codeChallenge?: string\n codeChallengeMethod?: string\n userId: string\n }\n>()\n\nconst refreshTokens = new Map<\n string,\n {\n createdAt: number\n userId: string\n email?: string\n }\n>()\n\n// AuthSession type for FastMCP authentication\ntype AuthSession = {\n userId: string\n email: string\n scope: string\n [key: string]: unknown // Allow additional properties\n}\n\ntype OAuthClientRegistrationRequest = {\n grant_types?: string[]\n response_types?: string[]\n redirect_uris?: string[]\n token_endpoint_auth_method?: string\n client_name?: string\n scope?: string\n}\n\ntype OAuthClientRegistrationResponse = {\n client_id: string\n client_secret: string\n client_id_issued_at: number\n client_secret_expires_at: number\n grant_types: string[]\n response_types: string[]\n redirect_uris: string[]\n token_endpoint_auth_method: string\n client_name?: string\n scope?: string\n}\n\nexport function createFastMCPServer(options: FastMCPServerOptions): {\n server: FastMCP\n duckpond: DuckPondServer\n} {\n log(\"🚀 Initializing FastMCP server...\")\n\n // Create DuckPond server instance\n const duckpond = new DuckPondServer(options.config)\n\n // Build server configuration\n const baseConfig = {\n name: \"duckpond\",\n version: packageJson.version as `${number}.${number}.${number}`,\n health: {\n enabled: true,\n path: \"/health\",\n status: 200,\n message: JSON.stringify({\n status: \"healthy\",\n service: \"duckpond-mcp-server\",\n version: packageJson.version,\n timestamp: new Date().toISOString(),\n }),\n },\n }\n\n // Create server with authentication (OAuth, Basic Auth, or none)\n const server =\n options.oauth?.enabled || options.basicAuth\n ? new FastMCP<AuthSession>({\n ...baseConfig,\n oauth: {\n enabled: true,\n authorizationServer: {\n issuer: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n authorizationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/authorize`,\n tokenEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/token`,\n jwksUri: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/jwks`,\n registrationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/register`,\n responseTypesSupported: [\"code\"],\n grantTypesSupported: [\"authorization_code\"],\n tokenEndpointAuthMethodsSupported: [\"client_secret_post\", \"client_secret_basic\"],\n codeChallengeMethodsSupported: [\"S256\", \"plain\"],\n },\n protectedResource: {\n resource:\n process.env.DUCKPOND_OAUTH_RESOURCE ||\n options.oauth?.resource ||\n `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n authorizationServers: [options.oauth?.issuer || `http://localhost:${options.port || 3000}`],\n },\n },\n authenticate: (request) => {\n const authHeader = request.headers?.authorization\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n // For OAuth-enabled servers, require authentication\n if (!authHeader) {\n if (options.oauth?.enabled) {\n // Return HTTP 401 with WWW-Authenticate header for proper OAuth discovery\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required. Please authenticate via OAuth.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n }\n\n // For non-OAuth servers, also require some form of auth\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n )\n }\n\n // Handle Basic Authentication\n if (options.basicAuth && authHeader.startsWith(\"Basic \")) {\n const credentials = Buffer.from(authHeader.slice(6), \"base64\").toString(\"utf-8\")\n const [username, password] = credentials.split(\":\")\n\n if (username === options.basicAuth.username && password === options.basicAuth.password) {\n return Promise.resolve({\n userId: options.basicAuth.userId || username,\n email: options.basicAuth.email || `${username}@example.com`,\n scope: \"read write\",\n })\n } else {\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid username or password\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Basic realm=\"MCP\"`,\n },\n },\n )\n }\n }\n\n // Handle Bearer Token (OAuth) - Validate JWT\n if (options.oauth?.enabled && authHeader.startsWith(\"Bearer \")) {\n const token = authHeader.slice(7) // Remove 'Bearer ' prefix\n\n try {\n // Verify JWT token\n const decoded = jwt.verify(token, JWT_SECRET) as jwt.JwtPayload\n\n if (!decoded.sub || !decoded.iat || !decoded.exp) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid token structure\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid token structure\"`,\n },\n },\n )\n }\n\n // Validate audience\n const expectedAudience = options.oauth?.resource || `${baseUrl}/mcp`\n if (decoded.aud && decoded.aud !== expectedAudience) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Token audience mismatch\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Token audience mismatch\"`,\n },\n },\n )\n }\n\n // Return user info from JWT claims\n return Promise.resolve({\n userId: decoded.sub,\n email: (decoded.email as string) || \"\",\n scope: (decoded.scope as string) || \"read write\",\n })\n } catch (error) {\n if (error instanceof Response) {\n throw error // Re-throw our custom Response errors\n }\n\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid or expired token\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid or expired token\"`,\n },\n },\n )\n }\n }\n\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid authorization header format\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n },\n })\n : new FastMCP(baseConfig)\n\n // Add query tool\n server.addTool({\n name: \"query\",\n description: \"Execute a SQL query for a specific user and return results\",\n parameters: querySchema,\n execute: async (args) => {\n try {\n const result = await duckpond.query(args.userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in query tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add execute tool\n server.addTool({\n name: \"execute\",\n description: \"Execute SQL statement (DDL/DML) for a specific user without returning results\",\n parameters: executeSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.execute(args.userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in execute tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add getUserStats tool\n server.addTool({\n name: \"getUserStats\",\n description: \"Get statistics about a user's database (memory usage, query count, etc.)\",\n parameters: getUserStatsSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.getUserStats(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in getUserStats tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add isAttached tool\n server.addTool({\n name: \"isAttached\",\n description: \"Check if a user's database is currently cached in memory\",\n parameters: isAttachedSchema,\n execute: async (args) => {\n try {\n const result = duckpond.isAttached(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n attached: result.data,\n userId: args.userId,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in isAttached tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add detachUser tool\n server.addTool({\n name: \"detachUser\",\n description: \"Manually detach a user's database from the cache to free resources\",\n parameters: detachUserSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.detachUser(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: `User ${args.userId} detached successfully`,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in detachUser tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add listUsers tool\n server.addTool({\n name: \"listUsers\",\n description: \"List all currently cached users and cache statistics\",\n parameters: listUsersSchema,\n execute: async () => {\n try {\n const result = duckpond.listUsers()\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(result.data, null, 2)\n } catch (error) {\n log(\"Error in listUsers tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add OAuth flow endpoints if OAuth is enabled\n if (options.oauth?.enabled) {\n setupOAuthEndpoints(server, options)\n }\n\n // Add root info endpoint using Hono\n const app = server.getApp()\n app.get(\"/\", (c) => {\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n const serverInfo = {\n name: \"DuckPond MCP Server\",\n version: packageJson.version,\n description: \"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage\",\n service: \"duckpond-mcp-server\",\n capabilities: {\n tools: [\"query\", \"execute\", \"getUserStats\", \"isAttached\", \"detachUser\", \"listUsers\"],\n transports: [\"stdio\", \"http\"],\n authentication: {\n oauth: options.oauth?.enabled || false,\n basicAuth: !!options.basicAuth,\n },\n },\n endpoints: {\n mcp: `${baseUrl}${options.endpoint || \"/mcp\"}`,\n health: `${baseUrl}/health`,\n ...(options.oauth?.enabled && {\n oauth: {\n authorization: `${baseUrl}/oauth/authorize`,\n token: `${baseUrl}/oauth/token`,\n jwks: `${baseUrl}/oauth/jwks`,\n register: `${baseUrl}/oauth/register`,\n },\n }),\n },\n timestamp: new Date().toISOString(),\n }\n\n return c.json(serverInfo)\n })\n\n log(\"✓ FastMCP server created\")\n\n return { server, duckpond }\n}\n\nfunction setupOAuthEndpoints(server: FastMCP, options: FastMCPServerOptions): void {\n const app = server.getApp()\n\n // Clean up old codes and refresh tokens every minute\n setInterval(() => {\n const now = Date.now()\n // Clean authorization codes (10 minutes)\n for (const [code, data] of authorizationCodes.entries()) {\n if (now - data.createdAt > 600000) {\n authorizationCodes.delete(code)\n }\n }\n // Clean refresh tokens (30 days)\n for (const [token, data] of refreshTokens.entries()) {\n if (now - data.createdAt > 2592000000) {\n refreshTokens.delete(token)\n }\n }\n }, 60000)\n\n // OAuth Authorization Endpoint - Login Form\n app.get(\"/oauth/authorize\", (c) => {\n const params = c.req.query()\n const responseType = params.response_type\n const redirectUri = params.redirect_uri\n const state = params.state\n const codeChallenge = params.code_challenge\n const codeChallengeMethod = params.code_challenge_method\n const clientId = params.client_id\n\n if (responseType !== \"code\") {\n return c.json(\n {\n error: \"unsupported_response_type\",\n error_description: \"Only 'code' response type is supported\",\n },\n 400,\n )\n }\n\n if (!redirectUri) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"redirect_uri is required\",\n },\n 400,\n )\n }\n\n // Validate PKCE parameters if present\n if (codeChallenge) {\n if (!codeChallengeMethod || ![\"S256\", \"plain\"].includes(codeChallengeMethod)) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Invalid code_challenge_method. Only 'S256' and 'plain' are supported\",\n },\n 400,\n )\n }\n }\n\n // Serve login form\n const loginForm = `\n<!DOCTYPE html>\n<html>\n<head>\n <title>OAuth Login - DuckPond MCP Server</title>\n <style>\n body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }\n .form-group { margin-bottom: 15px; }\n label { display: block; margin-bottom: 5px; font-weight: bold; }\n input[type=\"text\"], input[type=\"password\"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }\n button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }\n button:hover { background: #005a87; }\n .app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }\n </style>\n</head>\n<body>\n <div class=\"app-info\">\n <h3>🔐 OAuth Authorization</h3>\n <p><strong>Application:</strong> ${clientId || \"MCP Client\"}</p>\n <p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>\n </div>\n\n <form method=\"POST\" action=\"/oauth/authorize\">\n <input type=\"hidden\" name=\"response_type\" value=\"${responseType}\">\n <input type=\"hidden\" name=\"redirect_uri\" value=\"${redirectUri}\">\n <input type=\"hidden\" name=\"state\" value=\"${state || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge\" value=\"${codeChallenge || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge_method\" value=\"${codeChallengeMethod || \"\"}\">\n <input type=\"hidden\" name=\"client_id\" value=\"${clientId || \"\"}\">\n\n <div class=\"form-group\">\n <label for=\"username\">Username:</label>\n <input type=\"text\" id=\"username\" name=\"username\" required>\n </div>\n\n <div class=\"form-group\">\n <label for=\"password\">Password:</label>\n <input type=\"password\" id=\"password\" name=\"password\" required>\n </div>\n\n <button type=\"submit\">Authorize Application</button>\n </form>\n</body>\n</html>`\n\n return c.html(loginForm)\n })\n\n // OAuth Authorization POST - Process Login\n app.post(\"/oauth/authorize\", async (c) => {\n try {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n\n const username = params.get(\"username\")\n const password = params.get(\"password\")\n const redirectUri = params.get(\"redirect_uri\")\n const state = params.get(\"state\")\n const codeChallenge = params.get(\"code_challenge\")\n const codeChallengeMethod = params.get(\"code_challenge_method\")\n\n // Validate credentials\n if (username !== options.oauth?.username || password !== options.oauth?.password) {\n const errorForm = `\n<!DOCTYPE html>\n<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>\n<body><div class=\"error\">❌ Invalid username or password</div><a href=\"javascript:history.back()\">← Try Again</a></body></html>`\n return c.html(errorForm, 401)\n }\n\n // Generate authorization code\n const code = randomBytes(16).toString(\"hex\")\n authorizationCodes.set(code, {\n createdAt: Date.now(),\n redirectUri: redirectUri || \"\",\n codeChallenge: codeChallenge || undefined,\n codeChallengeMethod: codeChallengeMethod || undefined,\n userId: options.oauth?.userId || username || \"oauth-user\",\n })\n\n // Redirect with authorization code\n const redirectUrl = new URL(redirectUri || \"\")\n redirectUrl.searchParams.set(\"code\", code)\n if (state) {\n redirectUrl.searchParams.set(\"state\", state)\n }\n\n return c.redirect(redirectUrl.toString(), 302)\n } catch {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Failed to process authorization request\",\n },\n 400,\n )\n }\n })\n\n // OAuth Token Endpoint\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n const grantType = params.get(\"grant_type\")\n const code = params.get(\"code\")\n const redirectUri = params.get(\"redirect_uri\")\n const codeVerifier = params.get(\"code_verifier\")\n const refreshTokenParam = params.get(\"refresh_token\")\n\n if (grantType === \"refresh_token\") {\n // Handle refresh token flow\n if (!refreshTokenParam) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"refresh_token is required for refresh_token grant type\",\n },\n 400,\n )\n }\n\n const tokenData = refreshTokens.get(refreshTokenParam)\n if (!tokenData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired refresh token\",\n },\n 400,\n )\n }\n\n // Remove old refresh token (token rotation)\n refreshTokens.delete(refreshTokenParam)\n\n // Generate new JWT access token\n const accessTokenPayload = {\n sub: tokenData.userId,\n email: tokenData.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate new refresh token\n const newRefreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(newRefreshToken, {\n createdAt: Date.now(),\n userId: tokenData.userId,\n email: tokenData.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: newRefreshToken,\n })\n }\n\n if (grantType !== \"authorization_code\") {\n return c.json(\n {\n error: \"unsupported_grant_type\",\n error_description: \"Only 'authorization_code' and 'refresh_token' grant types are supported\",\n },\n 400,\n )\n }\n\n const codeData = authorizationCodes.get(code || \"\")\n if (!codeData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired authorization code\",\n },\n 400,\n )\n }\n\n // Validate redirect_uri matches\n if (codeData.redirectUri && codeData.redirectUri !== redirectUri) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"redirect_uri mismatch\",\n },\n 400,\n )\n }\n\n // Validate PKCE if code_challenge was provided\n if (codeData.codeChallenge) {\n if (!codeVerifier) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"code_verifier is required when code_challenge was used\",\n },\n 400,\n )\n }\n\n let expectedChallenge: string\n if (codeData.codeChallengeMethod === \"S256\") {\n expectedChallenge = createHash(\"sha256\").update(codeVerifier).digest().toString(\"base64url\")\n } else {\n // 'plain' method\n expectedChallenge = codeVerifier\n }\n\n if (expectedChallenge !== codeData.codeChallenge) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid code_verifier\",\n },\n 400,\n )\n }\n }\n\n // Remove used code\n authorizationCodes.delete(code!)\n\n // Generate JWT access token\n const accessTokenPayload = {\n sub: codeData.userId,\n email: options.oauth?.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate refresh token\n const refreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(refreshToken, {\n createdAt: Date.now(),\n userId: codeData.userId,\n email: options.oauth?.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: refreshToken,\n })\n })\n\n // JWKS Endpoint\n app.get(\"/oauth/jwks\", (c) => {\n return c.json({\n keys: [\n {\n kty: \"oct\", // Octet sequence for symmetric keys\n use: \"sig\",\n kid: \"duckpond-hmac-key\",\n alg: \"HS256\",\n },\n ],\n })\n })\n\n // Dynamic Client Registration\n app.post(\"/oauth/register\", async (c) => {\n try {\n let registrationRequest: OAuthClientRegistrationRequest = {}\n\n try {\n const body = await c.req.text()\n if (body && body !== \"[object Object]\") {\n try {\n registrationRequest = JSON.parse(body) as OAuthClientRegistrationRequest\n } catch {\n const formData = Object.fromEntries(new URLSearchParams(body))\n registrationRequest = formData as OAuthClientRegistrationRequest\n }\n }\n } catch (parseError) {\n log(\"Error parsing request body:\", parseError)\n }\n\n const clientId = `client-${randomBytes(8).toString(\"hex\")}`\n const clientSecret = randomBytes(16).toString(\"hex\")\n\n const response: OAuthClientRegistrationResponse = {\n client_id: clientId,\n client_secret: clientSecret,\n client_id_issued_at: Math.floor(Date.now() / 1000),\n client_secret_expires_at: 0, // Never expires\n grant_types: registrationRequest.grant_types || [\"authorization_code\"],\n response_types: registrationRequest.response_types || [\"code\"],\n redirect_uris: registrationRequest.redirect_uris || [],\n token_endpoint_auth_method: registrationRequest.token_endpoint_auth_method || \"client_secret_post\",\n }\n\n if (registrationRequest.client_name) {\n response.client_name = registrationRequest.client_name\n }\n if (registrationRequest.scope) {\n response.scope = registrationRequest.scope\n }\n\n return c.json(response, 201)\n } catch (error) {\n return c.json(\n {\n error: \"invalid_client_metadata\",\n error_description:\n \"Invalid client registration request: \" + (error instanceof Error ? error.message : String(error)),\n },\n 400,\n )\n }\n })\n\n log(\"✓ OAuth flow endpoints added\")\n}\nexport async function startServer(options: FastMCPServerOptions, transport: \"stdio\" | \"http\"): Promise<void> {\n const { server, duckpond } = createFastMCPServer(options)\n\n // Initialize DuckPond\n const initResult = await duckpond.init()\n if (!initResult.success) {\n throw new Error(`Failed to initialize DuckPond: ${initResult.error.message}`)\n }\n\n log(\"DuckPond initialized successfully\")\n\n // Start the server with appropriate transport\n if (transport === \"stdio\") {\n await server.start({\n transportType: \"stdio\",\n })\n log(\"✓ FastMCP server running with stdio transport\")\n } else {\n await server.start({\n transportType: \"httpStream\",\n httpStream: {\n port: options.port || 3000,\n endpoint: (options.endpoint || \"/mcp\") as `/${string}`,\n },\n })\n log(`✓ FastMCP server running on http://0.0.0.0:${options.port || 3000}${options.endpoint || \"/mcp\"}`)\n log(\"🔌 Connect with StreamableHTTPClientTransport\")\n }\n\n // Handle cleanup on exit\n process.on(\"SIGINT\", async () => {\n log(\"Received SIGINT, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n\n process.on(\"SIGTERM\", async () => {\n log(\"Received SIGTERM, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n}\n"],"mappings":"2JACA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,uBACxB,OAAS,cAAAC,EAAY,eAAAC,MAAmB,SACxC,OAAS,iBAAAC,MAAqB,SAI9B,UAAYC,MAAS,eACrB,OAAS,OAAAC,MAAW,MAXf,WAAW,SACd,WAAW,OAASC,GAOtB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EAAcF,EAAQ,iBAAiB,EAgBvCG,EAAMC,EAAQ,QA0BdC,EAAa,QAAQ,IAAI,qBAAuBC,EAAY,EAAE,EAAE,SAAS,KAAK,EAG9EC,EAAiB,QAAQ,IAAI,wBAC/B,SAAS,QAAQ,IAAI,wBAAyB,EAAE,EAChD,IAAM,GAAK,GAAK,GAGdC,EAAqB,IAAI,IAWzBC,EAAgB,IAAI,IAuCnB,SAASC,EAAoBC,EAGlC,CACAR,EAAI,0CAAmC,EAGvC,IAAMS,EAAW,IAAIC,EAAeF,EAAQ,MAAM,EAG5CG,EAAa,CACjB,KAAM,WACN,QAASZ,EAAY,QACrB,OAAQ,CACN,QAAS,GACT,KAAM,UACN,OAAQ,IACR,QAAS,KAAK,UAAU,CACtB,OAAQ,UACR,QAAS,sBACT,QAASA,EAAY,QACrB,UAAW,IAAI,KAAK,EAAE,YAAY,CACpC,CAAC,CACH,CACF,EAGMa,EACJJ,EAAQ,OAAO,SAAWA,EAAQ,U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,CAAC,CAChB,CAAC,CACH","names":["webcrypto","FastMCP","createHash","randomBytes","createRequire","jwt","URL","webcrypto","require","createRequire","packageJson","log","loggers","JWT_SECRET","randomBytes","JWT_EXPIRES_IN","authorizationCodes","refreshTokens","createFastMCPServer","options","duckpond","DuckPondServer","baseConfig","server","FastMCP","request","authHeader","baseUrl","credentials","username","password","token","decoded","expectedAudience","error","querySchema","args","result","errorMessage","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","setupOAuthEndpoints","c","serverInfo","app","now","code","data","params","responseType","redirectUri","state","codeChallenge","codeChallengeMethod","clientId","loginForm","body","redirectUrl","URL","grantType","codeVerifier","refreshTokenParam","tokenData","accessTokenPayload","newRefreshToken","accessToken","codeData","expectedChallenge","createHash","refreshToken","registrationRequest","parseError","clientSecret","response","startServer","transport","initResult"]}
|