duckpond-mcp-server 0.3.0 → 0.3.1
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-VGBI52XK.js → chunk-JXCFUXVK.js} +6 -6
- package/dist/{chunk-VGBI52XK.js.map → chunk-JXCFUXVK.js.map} +1 -1
- package/dist/chunk-VSQCOL7H.js +2 -0
- package/dist/chunk-VSQCOL7H.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/ui-server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-SIVPP6RP.js +0 -2
- package/dist/chunk-SIVPP6RP.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as A}from"./chunk-R65UMTEX.js";import{a as
|
|
1
|
+
import{a as A}from"./chunk-R65UMTEX.js";import{a as D}from"./chunk-VSQCOL7H.js";import{b as y,c as C,d as $,e as T,f as O,g as P,h as E}from"./chunk-MPMUZFRC.js";import{b as k}from"./chunk-A3S6D44B.js";import{webcrypto as z}from"crypto";import{FastMCP as q}from"@jordanburke/fastmcp";import{createHash as N,randomBytes as w}from"crypto";import{createRequire as J}from"module";import*as S from"jsonwebtoken";import{URL as x}from"url";globalThis.crypto||(globalThis.crypto=z);var F=J(import.meta.url),I=F("../package.json"),d=k.fastmcp,R=process.env.DUCKPOND_JWT_SECRET||w(32).toString("hex"),b=process.env.DUCKPOND_JWT_EXPIRES_IN?parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN,10):365*24*60*60,v=new Map,_=new Map;function W(s){d("\u{1F680} Initializing FastMCP server...");let a=new A(s.config),h={name:"duckpond",version:I.version,health:{enabled:!0,path:"/health",status:200,message:JSON.stringify({status:"healthy",service:"duckpond-mcp-server",version:I.version,timestamp:new Date().toISOString()})}},o=s.oauth?.enabled||s.basicAuth?new q({...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:e=>{let r=e.headers?.authorization,t=s.oauth?.issuer||`http://localhost:${s.port||3e3}`;if(!r)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="${t}/oauth/authorize", resource="${t}/.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&&r.startsWith("Basic ")){let c=Buffer.from(r.slice(6),"base64").toString("utf-8"),[i,l]=c.split(":");if(i===s.basicAuth.username&&l===s.basicAuth.password)return Promise.resolve({userId:s.basicAuth.userId||i,email:s.basicAuth.email||`${i}@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&&r.startsWith("Bearer ")){let c=r.slice(7);try{let i=S.verify(c,R);if(!i.sub||!i.iat||!i.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 l=s.oauth?.resource||`${t}/mcp`;if(i.aud&&i.aud!==l)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:i.sub,email:i.email||"",scope:i.scope||"read write"})}catch(i){throw i instanceof Response?i: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="${t}/oauth/authorize", resource="${t}/.well-known/oauth-protected-resource"`}})}}):new q(h);o.addTool({name:"query",description:"Execute a SQL query for a specific user and return results",parameters:C,execute:async e=>{try{let r=y(e.userId),t=await a.query(r,e.sql);return t.success?JSON.stringify({rows:t.data,rowCount:t.data.length,executionTime:t.executionTime},null,2):`ERROR: ${t.error.message}`}catch(r){d("Error in query tool:",r);let t=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"execute",description:"Execute SQL statement (DDL/DML) for a specific user without returning results",parameters:$,execute:async e=>{try{let r=y(e.userId),t=await a.execute(r,e.sql);return t.success?JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:t.executionTime},null,2):`ERROR: ${t.error.message}`}catch(r){d("Error in execute tool:",r);let t=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"getUserStats",description:"Get statistics about a user's database (memory usage, query count, etc.)",parameters:T,execute:async e=>{try{let r=y(e.userId),t=await a.getUserStats(r);return t.success?JSON.stringify({...t.data,lastAccess:t.data.lastAccess.toISOString()},null,2):`ERROR: ${t.error.message}`}catch(r){d("Error in getUserStats tool:",r);let t=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"isAttached",description:"Check if a user's database is currently cached in memory",parameters:O,execute:async e=>{try{let r=y(e.userId),t=a.isAttached(r);return t.success?JSON.stringify({attached:t.data,userId:r},null,2):`ERROR: ${t.error.message}`}catch(r){d("Error in isAttached tool:",r);let t=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"detachUser",description:"Manually detach a user's database from the cache to free resources",parameters:P,execute:async e=>{try{let r=y(e.userId),t=await a.detachUser(r);return t.success?JSON.stringify({success:!0,message:`User ${r} detached successfully`},null,2):`ERROR: ${t.error.message}`}catch(r){d("Error in detachUser tool:",r);let t=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"listUsers",description:"List all currently cached users and cache statistics",parameters:E,execute:async()=>{try{let e=a.listUsers();return e.success?JSON.stringify(e.data,null,2):`ERROR: ${e.error.message}`}catch(e){d("Error in listUsers tool:",e);let r=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:r},null,2)}`}}}),s.oauth?.enabled&&B(o,s);let n=o.getApp();return n.get("/",e=>{let r=s.oauth?.issuer||`http://localhost:${s.port||3e3}`,t={name:"DuckPond MCP Server",version:I.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:`${r}${s.endpoint||"/mcp"}`,health:`${r}/health`,ui:`${r}/ui/:userId`,...s.oauth?.enabled&&{oauth:{authorization:`${r}/oauth/authorize`,token:`${r}/oauth/token`,jwks:`${r}/oauth/jwks`,register:`${r}/oauth/register`}}},timestamp:new Date().toISOString()};return e.json(t)}),L(n,a,s),d("\u2713 FastMCP server created"),{server:o,duckpond:a}}function B(s,a){let h=s.getApp();setInterval(()=>{let o=Date.now();for(let[n,e]of v.entries())o-e.createdAt>6e5&&v.delete(n);for(let[n,e]of _.entries())o-e.createdAt>2592e6&&_.delete(n)},6e4),h.get("/oauth/authorize",o=>{let n=o.req.query(),e=n.response_type,r=n.redirect_uri,t=n.state,c=n.code_challenge,i=n.code_challenge_method,l=n.client_id;if(e!=="code")return o.json({error:"unsupported_response_type",error_description:"Only 'code' response type is supported"},400);if(!r)return o.json({error:"invalid_request",error_description:"redirect_uri is required"},400);if(c&&(!i||!["S256","plain"].includes(i)))return o.json({error:"invalid_request",error_description:"Invalid code_challenge_method. Only 'S256' and 'plain' are supported"},400);let u=`
|
|
2
2
|
<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
@@ -21,8 +21,8 @@ import{a as A}from"./chunk-R65UMTEX.js";import{a as E}from"./chunk-SIVPP6RP.js";
|
|
|
21
21
|
</div>
|
|
22
22
|
|
|
23
23
|
<form method="POST" action="/oauth/authorize">
|
|
24
|
-
<input type="hidden" name="response_type" value="${
|
|
25
|
-
<input type="hidden" name="redirect_uri" value="${
|
|
24
|
+
<input type="hidden" name="response_type" value="${e}">
|
|
25
|
+
<input type="hidden" name="redirect_uri" value="${r}">
|
|
26
26
|
<input type="hidden" name="state" value="${t||""}">
|
|
27
27
|
<input type="hidden" name="code_challenge" value="${c||""}">
|
|
28
28
|
<input type="hidden" name="code_challenge_method" value="${i||""}">
|
|
@@ -41,8 +41,8 @@ import{a as A}from"./chunk-R65UMTEX.js";import{a as E}from"./chunk-SIVPP6RP.js";
|
|
|
41
41
|
<button type="submit">Authorize Application</button>
|
|
42
42
|
</form>
|
|
43
43
|
</body>
|
|
44
|
-
</html>`;return o.html(
|
|
44
|
+
</html>`;return o.html(u)}),h.post("/oauth/authorize",async o=>{try{let n=await o.req.text(),e=new URLSearchParams(n),r=e.get("username"),t=e.get("password"),c=e.get("redirect_uri"),i=e.get("state"),l=e.get("code_challenge"),u=e.get("code_challenge_method");if(r!==a.oauth?.username||t!==a.oauth?.password)return o.html(`
|
|
45
45
|
<!DOCTYPE html>
|
|
46
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
|
|
48
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
<body><div class="error">\u274C Invalid username or password</div><a href="javascript:history.back()">\u2190 Try Again</a></body></html>`,401);let m=w(16).toString("hex");v.set(m,{createdAt:Date.now(),redirectUri:c||"",codeChallenge:l||void 0,codeChallengeMethod:u||void 0,userId:a.oauth?.userId||r||"oauth-user"});let p=new x(c||"");return p.searchParams.set("code",m),i&&p.searchParams.set("state",i),o.redirect(p.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(),e=new URLSearchParams(n),r=e.get("grant_type"),t=e.get("code"),c=e.get("redirect_uri"),i=e.get("code_verifier"),l=e.get("refresh_token");if(r==="refresh_token"){if(!l)return o.json({error:"invalid_request",error_description:"refresh_token is required for refresh_token grant type"},400);let f=_.get(l);if(!f)return o.json({error:"invalid_grant",error_description:"Invalid or expired refresh token"},400);_.delete(l);let M={sub:f.userId,email:f.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:a.oauth?.issuer||`http://localhost:${a.port||3e3}`,aud:a.oauth?.resource||`${a.oauth?.issuer||`http://localhost:${a.port||3e3}`}/mcp`},U=w(32).toString("hex");_.set(U,{createdAt:Date.now(),userId:f.userId,email:f.email});let j=S.sign(M,R);return o.json({access_token:j,token_type:"Bearer",expires_in:b,scope:"read write",refresh_token:U})}if(r!=="authorization_code")return o.json({error:"unsupported_grant_type",error_description:"Only 'authorization_code' and 'refresh_token' grant types are supported"},400);let u=v.get(t||"");if(!u)return o.json({error:"invalid_grant",error_description:"Invalid or expired authorization code"},400);if(u.redirectUri&&u.redirectUri!==c)return o.json({error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(u.codeChallenge){if(!i)return o.json({error:"invalid_grant",error_description:"code_verifier is required when code_challenge was used"},400);let f;if(u.codeChallengeMethod==="S256"?f=N("sha256").update(i).digest().toString("base64url"):f=i,f!==u.codeChallenge)return o.json({error:"invalid_grant",error_description:"Invalid code_verifier"},400)}v.delete(t);let m={sub:u.userId,email:a.oauth?.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:a.oauth?.issuer||`http://localhost:${a.port||3e3}`,aud:a.oauth?.resource||`${a.oauth?.issuer||`http://localhost:${a.port||3e3}`}/mcp`},p=w(32).toString("hex");_.set(p,{createdAt:Date.now(),userId:u.userId,email:a.oauth?.email});let g=S.sign(m,R);return o.json({access_token:g,token_type:"Bearer",expires_in:b,scope:"read write",refresh_token:p})}),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){d("Error parsing request body:",c)}let e=`client-${w(8).toString("hex")}`,r=w(16).toString("hex"),t={client_id:e,client_secret:r,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&&(t.client_name=n.client_name),n.scope&&(t.scope=n.scope),o.json(t,201)}catch(n){return o.json({error:"invalid_client_metadata",error_description:"Invalid client registration request: "+(n instanceof Error?n.message:String(n))},400)}}),d("\u2713 OAuth flow endpoints added")}function L(s,a,h){let o=h.oauth?.issuer||`http://localhost:${h.port||3e3}`,n=a.getUIPort();s.get("/ui",e=>{if(!a.getCurrentUIUser()){let t=a.listUsers();return e.json({message:"No UI active. Visit /ui/:userId to start DuckDB UI for a user.",currentUser:null,availableUsers:t.success?t.data.users:[],endpoints:{startUI:`${o}/ui/:userId`}})}return e.redirect("/ui/")}),s.get("/ui/:userId",async e=>{let r=e.req.param("userId");d(`Starting UI for user: ${r}`);let t=await a.startUI(r);return t.success?e.redirect("/ui/"):e.json({error:"Failed to start UI",message:t.error.message,details:t.error.details},500)}),s.all("/ui/*",async e=>{if(!a.getCurrentUIUser())return e.json({error:"No UI active",message:"Start UI by visiting /ui/:userId first"},400);let t=e.req.path.replace(/^\/ui/,"")||"/";try{let c=`http://localhost:${n}${t}`,i=new x(e.req.url);i.search;let l=new Headers;e.req.raw.headers.forEach((p,g)=>{g.toLowerCase()!=="host"&&l.set(g,p)});let u=await fetch(c+i.search,{method:e.req.method,headers:l,body:["GET","HEAD"].includes(e.req.method)?void 0:await e.req.arrayBuffer()}),m=new Headers;return u.headers.forEach((p,g)=>{["transfer-encoding","connection"].includes(g.toLowerCase())||m.set(g,p)}),new Response(u.body,{status:u.status,statusText:u.statusText,headers:m})}catch(c){return d(`UI proxy error: ${c instanceof Error?c.message:String(c)}`),e.json({error:"UI proxy error",message:c instanceof Error?c.message:"Failed to connect to DuckDB UI",hint:"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it."},502)}}),s.all("*",async e=>{if(!a.getCurrentUIUser())return e.notFound();let t=e.req.path;if(!t.match(/\.(js|css|json|woff2?|ttf|svg|png|ico)$/)&&!t.includes("hatchling"))return e.notFound();try{let c=`http://localhost:${n}${t}`,i=new x(e.req.url),l=new Headers;e.req.raw.headers.forEach((p,g)=>{g.toLowerCase()!=="host"&&l.set(g,p)});let u=await fetch(c+i.search,{method:e.req.method,headers:l,body:["GET","HEAD"].includes(e.req.method)?void 0:await e.req.arrayBuffer()}),m=new Headers;return u.headers.forEach((p,g)=>{["transfer-encoding","connection"].includes(g.toLowerCase())||m.set(g,p)}),new Response(u.body,{status:u.status,statusText:u.statusText,headers:m})}catch{return e.notFound()}}),d("\u2713 UI endpoints added")}async function te(s,a){let{server:h,duckpond:o}=W(s),n=await o.init();if(!n.success)throw new Error(`Failed to initialize DuckPond: ${n.error.message}`);d("DuckPond initialized successfully"),s.ui?.internalPort&&o.setUIPort(s.ui.internalPort),a==="stdio"?(await h.start({transportType:"stdio"}),d("\u2713 FastMCP server running with stdio transport"),s.ui?.enabled&&await D({port:s.ui.port,duckpond:o})):(await h.start({transportType:"httpStream",httpStream:{port:s.port||3e3,endpoint:s.endpoint||"/mcp"}}),d(`\u2713 FastMCP server running on http://0.0.0.0:${s.port||3e3}${s.endpoint||"/mcp"}`),d("\u{1F50C} Connect with StreamableHTTPClientTransport")),process.on("SIGINT",async()=>{d("Received SIGINT, closing server..."),await o.close(),process.exit(0)}),process.on("SIGTERM",async()=>{d("Received SIGTERM, closing server..."),await o.close(),process.exit(0)})}export{W as a,te as b};
|
|
48
|
+
//# sourceMappingURL=chunk-JXCFUXVK.js.map
|
|
@@ -1 +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 { startUIServer } from \"./ui-server\"\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 ui?: {\n enabled: boolean\n port: number\n internalPort?: number\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 ui: `${baseUrl}/ui/:userId`,\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 // Add UI endpoints for DuckDB UI access\n setupUIEndpoints(app, duckpond, options)\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}\n\nfunction setupUIEndpoints(\n app: ReturnType<FastMCP[\"getApp\"]>,\n duckpond: DuckPondServer,\n options: FastMCPServerOptions,\n): void {\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n const uiInternalPort = duckpond.getUIPort()\n\n // GET /ui - Info endpoint when no UI running, or redirect to UI\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n const listResult = duckpond.listUsers()\n return c.json({\n message: \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser: null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `${baseUrl}/ui/:userId`,\n },\n })\n }\n // Redirect to the UI root\n return c.redirect(\"/ui/\")\n })\n\n // GET /ui/:userId - Start UI for a specific user and redirect\n app.get(\"/ui/:userId\", async (c) => {\n const userId = c.req.param(\"userId\")\n\n log(`Starting UI for user: ${userId}`)\n const result = await duckpond.startUI(userId)\n\n if (!result.success) {\n return c.json(\n {\n error: \"Failed to start UI\",\n message: result.error.message,\n details: result.error.details,\n },\n 500,\n )\n }\n\n // Redirect to the UI\n return c.redirect(\"/ui/\")\n })\n\n // ALL /ui/* - Proxy requests to DuckDB UI server\n app.all(\"/ui/*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.json(\n {\n error: \"No UI active\",\n message: \"Start UI by visiting /ui/:userId first\",\n },\n 400,\n )\n }\n\n // Get the path after /ui\n const path = c.req.path.replace(/^\\/ui/, \"\") || \"/\"\n\n try {\n // Build the proxy URL\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n if (url.search) {\n // Append query string if present\n }\n\n // Prepare headers, filtering out host\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n // Make the proxy request\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n // Return the proxied response\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n // Don't forward certain headers\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch (error) {\n log(`UI proxy error: ${error instanceof Error ? error.message : String(error)}`)\n return c.json(\n {\n error: \"UI proxy error\",\n message: error instanceof Error ? error.message : \"Failed to connect to DuckDB UI\",\n hint: \"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it.\",\n },\n 502,\n )\n }\n })\n\n log(\"✓ UI endpoints added\")\n}\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 // Set UI internal port if configured\n if (options.ui?.internalPort) {\n duckpond.setUIPort(options.ui.internalPort)\n }\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\n // Start UI server if enabled in stdio mode\n if (options.ui?.enabled) {\n await startUIServer({\n port: options.ui.port,\n duckpond,\n })\n }\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":"0MACA,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,EAmBvCG,EAAMC,EAAQ,QA+BdC,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,CACv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OAAOA,CAAK,CAAC,EAAE,EACxEc,EAAE,KACP,CACE,MAAO,iBACP,QAASd,aAAiB,MAAQA,EAAM,QAAU,iCAClD,KAAM,kFACR,EACA,GACF,CACF,CACF,CAAC,EAEDvB,EAAI,2BAAsB,CAC5B,CAEA,eAAsB8E,GAAYtE,EAA+BuE,EAA4C,CAC3G,GAAM,CAAE,OAAAnE,EAAQ,SAAAH,CAAS,EAAIF,EAAoBC,CAAO,EAGlDwE,EAAa,MAAMvE,EAAS,KAAK,EACvC,GAAI,CAACuE,EAAW,QACd,MAAM,IAAI,MAAM,kCAAkCA,EAAW,MAAM,OAAO,EAAE,EAG9EhF,EAAI,mCAAmC,EAGnCQ,EAAQ,IAAI,cACdC,EAAS,UAAUD,EAAQ,GAAG,YAAY,EAIxCuE,IAAc,SAChB,MAAMnE,EAAO,MAAM,CACjB,cAAe,OACjB,CAAC,EACDZ,EAAI,oDAA+C,EAG/CQ,EAAQ,IAAI,SACd,MAAMyE,EAAc,CAClB,KAAMzE,EAAQ,GAAG,KACjB,SAAAC,CACF,CAAC,IAGH,MAAMG,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","app","c","serverInfo","setupUIEndpoints","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","uiInternalPort","listResult","path","proxyUrl","url","headers","value","key","responseHeaders","startServer","transport","initResult","startUIServer"]}
|
|
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 { startUIServer } from \"./ui-server\"\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 ui?: {\n enabled: boolean\n port: number\n internalPort?: number\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 ui: `${baseUrl}/ui/:userId`,\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 // Add UI endpoints for DuckDB UI access\n setupUIEndpoints(app, duckpond, options)\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}\n\nfunction setupUIEndpoints(\n app: ReturnType<FastMCP[\"getApp\"]>,\n duckpond: DuckPondServer,\n options: FastMCPServerOptions,\n): void {\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n const uiInternalPort = duckpond.getUIPort()\n\n // GET /ui - Info endpoint when no UI running, or redirect to UI\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n const listResult = duckpond.listUsers()\n return c.json({\n message: \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser: null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `${baseUrl}/ui/:userId`,\n },\n })\n }\n // Redirect to the UI root\n return c.redirect(\"/ui/\")\n })\n\n // GET /ui/:userId - Start UI for a specific user and redirect\n app.get(\"/ui/:userId\", async (c) => {\n const userId = c.req.param(\"userId\")\n\n log(`Starting UI for user: ${userId}`)\n const result = await duckpond.startUI(userId)\n\n if (!result.success) {\n return c.json(\n {\n error: \"Failed to start UI\",\n message: result.error.message,\n details: result.error.details,\n },\n 500,\n )\n }\n\n // Redirect to the UI\n return c.redirect(\"/ui/\")\n })\n\n // ALL /ui/* - Proxy requests to DuckDB UI server\n app.all(\"/ui/*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.json(\n {\n error: \"No UI active\",\n message: \"Start UI by visiting /ui/:userId first\",\n },\n 400,\n )\n }\n\n // Get the path after /ui\n const path = c.req.path.replace(/^\\/ui/, \"\") || \"/\"\n\n try {\n // Build the proxy URL\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n if (url.search) {\n // Append query string if present\n }\n\n // Prepare headers, filtering out host\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n // Make the proxy request\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n // Return the proxied response\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n // Don't forward certain headers\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch (error) {\n log(`UI proxy error: ${error instanceof Error ? error.message : String(error)}`)\n return c.json(\n {\n error: \"UI proxy error\",\n message: error instanceof Error ? error.message : \"Failed to connect to DuckDB UI\",\n hint: \"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it.\",\n },\n 502,\n )\n }\n })\n\n // Fallback: Proxy unknown paths to DuckDB UI (for assets like JS/CSS)\n // DuckDB UI uses <base href=\"/\"> so assets are requested at root\n // Only proxy if UI is active and path looks like a DuckDB UI asset\n app.all(\"*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.notFound()\n }\n\n const path = c.req.path\n\n // Only proxy paths that look like DuckDB UI assets\n if (!path.match(/\\.(js|css|json|woff2?|ttf|svg|png|ico)$/) && !path.includes(\"hatchling\")) {\n return c.notFound()\n }\n\n try {\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch {\n return c.notFound()\n }\n })\n\n log(\"✓ UI endpoints added\")\n}\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 // Set UI internal port if configured\n if (options.ui?.internalPort) {\n duckpond.setUIPort(options.ui.internalPort)\n }\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\n // Start UI server if enabled in stdio mode\n if (options.ui?.enabled) {\n await startUIServer({\n port: options.ui.port,\n duckpond,\n })\n }\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":"0MACA,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,EAmBvCG,EAAMC,EAAQ,QA+BdC,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,EAA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C,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","app","c","serverInfo","setupUIEndpoints","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","uiInternalPort","listResult","path","proxyUrl","url","headers","value","key","responseHeaders","startServer","transport","initResult","startUIServer"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as I}from"./chunk-A3S6D44B.js";import{serve as g}from"@hono/node-server";import{Hono as m}from"hono";var U=I.core;async function D(f){let{port:i,duckpond:n}=f,p=n.getUIPort(),c=new m;c.get("/ui",e=>{if(!n.getCurrentUIUser()){let t=n.listUsers();return e.json({message:"No UI active. Visit /ui/:userId to start DuckDB UI for a user.",currentUser:null,availableUsers:t.success?t.data.users:[],endpoints:{startUI:`http://localhost:${i}/ui/:userId`}})}return e.redirect("/ui/")}),c.get("/ui/:userId",async e=>{let a=e.req.param("userId");U(`[UI Server] Starting UI for user: ${a}`);let t=await n.startUI(a);return t.success?e.redirect("/ui/"):e.json({error:"Failed to start UI",message:t.error.message,details:t.error.details},500)}),c.all("/ui/*",async e=>{if(!n.getCurrentUIUser())return e.json({error:"No UI active",message:"Start UI by visiting /ui/:userId first"},400);let t=e.req.path.replace(/^\/ui/,"")||"/";try{let s=`http://localhost:${p}${t}`,l=new URL(e.req.url),d=new Headers;e.req.raw.headers.forEach((u,r)=>{r.toLowerCase()!=="host"&&d.set(r,u)});let o=await fetch(s+l.search,{method:e.req.method,headers:d,body:["GET","HEAD"].includes(e.req.method)?void 0:await e.req.arrayBuffer()}),h=new Headers;return o.headers.forEach((u,r)=>{["transfer-encoding","connection"].includes(r.toLowerCase())||h.set(r,u)}),new Response(o.body,{status:o.status,statusText:o.statusText,headers:h})}catch(s){return U(`[UI Server] Proxy error: ${s instanceof Error?s.message:String(s)}`),e.json({error:"UI proxy error",message:s instanceof Error?s.message:"Failed to connect to DuckDB UI",hint:"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it."},502)}}),c.get("/",e=>{let a=n.getCurrentUIUser();return e.json({name:"DuckPond UI Server",description:"Lightweight HTTP server for DuckDB UI access in stdio mode",currentUIUser:a,endpoints:{ui:`http://localhost:${i}/ui/:userId`,uiRoot:`http://localhost:${i}/ui/`}})}),c.all("*",async e=>{if(!n.getCurrentUIUser())return e.notFound();let t=e.req.path;try{let s=`http://localhost:${p}${t}`,l=new URL(e.req.url),d=new Headers;e.req.raw.headers.forEach((u,r)=>{r.toLowerCase()!=="host"&&d.set(r,u)});let o=await fetch(s+l.search,{method:e.req.method,headers:d,body:["GET","HEAD"].includes(e.req.method)?void 0:await e.req.arrayBuffer()}),h=new Headers;return o.headers.forEach((u,r)=>{["transfer-encoding","connection"].includes(r.toLowerCase())||h.set(r,u)}),new Response(o.body,{status:o.status,statusText:o.statusText,headers:h})}catch{return e.notFound()}}),g({fetch:c.fetch,port:i}),U(`\u2713 UI server running at http://localhost:${i}/ui`),U(` Visit http://localhost:${i}/ui/:userId to start DuckDB UI`)}export{D as a};
|
|
2
|
+
//# sourceMappingURL=chunk-VSQCOL7H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ui-server.ts"],"sourcesContent":["import { serve } from \"@hono/node-server\"\nimport { Hono } from \"hono\"\n\nimport type { DuckPondServer } from \"./server-core\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.core\n\nexport type UIServerOptions = {\n port: number\n duckpond: DuckPondServer\n}\n\n/**\n * Start a lightweight HTTP server for UI access in stdio mode\n * This allows accessing DuckDB UI even when MCP is running over stdio\n */\nexport async function startUIServer(options: UIServerOptions): Promise<void> {\n const { port, duckpond } = options\n const uiInternalPort = duckpond.getUIPort()\n\n const app = new Hono()\n\n // GET /ui - Info endpoint when no UI running, or redirect to UI\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n const listResult = duckpond.listUsers()\n return c.json({\n message: \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser: null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `http://localhost:${port}/ui/:userId`,\n },\n })\n }\n // Redirect to the UI root\n return c.redirect(\"/ui/\")\n })\n\n // GET /ui/:userId - Start UI for a specific user and redirect\n app.get(\"/ui/:userId\", async (c) => {\n const userId = c.req.param(\"userId\")\n\n log(`[UI Server] Starting UI for user: ${userId}`)\n const result = await duckpond.startUI(userId)\n\n if (!result.success) {\n return c.json(\n {\n error: \"Failed to start UI\",\n message: result.error.message,\n details: result.error.details,\n },\n 500,\n )\n }\n\n // Redirect to the UI\n return c.redirect(\"/ui/\")\n })\n\n // ALL /ui/* - Proxy requests to DuckDB UI server\n app.all(\"/ui/*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.json(\n {\n error: \"No UI active\",\n message: \"Start UI by visiting /ui/:userId first\",\n },\n 400,\n )\n }\n\n // Get the path after /ui\n const path = c.req.path.replace(/^\\/ui/, \"\") || \"/\"\n\n try {\n // Build the proxy URL\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n\n // Prepare headers, filtering out host\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n // Make the proxy request\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n // Return the proxied response\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n // Don't forward certain headers\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch (error) {\n log(`[UI Server] Proxy error: ${error instanceof Error ? error.message : String(error)}`)\n return c.json(\n {\n error: \"UI proxy error\",\n message: error instanceof Error ? error.message : \"Failed to connect to DuckDB UI\",\n hint: \"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it.\",\n },\n 502,\n )\n }\n })\n\n // Root endpoint with info\n app.get(\"/\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n return c.json({\n name: \"DuckPond UI Server\",\n description: \"Lightweight HTTP server for DuckDB UI access in stdio mode\",\n currentUIUser: currentUser,\n endpoints: {\n ui: `http://localhost:${port}/ui/:userId`,\n uiRoot: `http://localhost:${port}/ui/`,\n },\n })\n })\n\n // Fallback: Proxy unknown paths to DuckDB UI (for assets like JS/CSS)\n // DuckDB UI uses <base href=\"/\"> so assets are requested at root\n app.all(\"*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.notFound()\n }\n\n const path = c.req.path\n\n try {\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch {\n return c.notFound()\n }\n })\n\n // Start the server\n serve({\n fetch: app.fetch,\n port,\n })\n\n log(`✓ UI server running at http://localhost:${port}/ui`)\n log(` Visit http://localhost:${port}/ui/:userId to start DuckDB UI`)\n}\n"],"mappings":"wCAAA,OAAS,SAAAA,MAAa,oBACtB,OAAS,QAAAC,MAAY,OAKrB,IAAMC,EAAMC,EAAQ,KAWpB,eAAsBC,EAAcC,EAAyC,CAC3E,GAAM,CAAE,KAAAC,EAAM,SAAAC,CAAS,EAAIF,EACrBG,EAAiBD,EAAS,UAAU,EAEpCE,EAAM,IAAIC,EAGhBD,EAAI,IAAI,MAAQE,GAAM,CAEpB,GAAI,CADgBJ,EAAS,iBAAiB,EAC5B,CAChB,IAAMK,EAAaL,EAAS,UAAU,EACtC,OAAOI,EAAE,KAAK,CACZ,QAAS,iEACT,YAAa,KACb,eAAgBC,EAAW,QAAUA,EAAW,KAAK,MAAQ,CAAC,EAC9D,UAAW,CACT,QAAS,oBAAoBN,CAAI,aACnC,CACF,CAAC,CACH,CAEA,OAAOK,EAAE,SAAS,MAAM,CAC1B,CAAC,EAGDF,EAAI,IAAI,cAAe,MAAOE,GAAM,CAClC,IAAME,EAASF,EAAE,IAAI,MAAM,QAAQ,EAEnCT,EAAI,qCAAqCW,CAAM,EAAE,EACjD,IAAMC,EAAS,MAAMP,EAAS,QAAQM,CAAM,EAE5C,OAAKC,EAAO,QAYLH,EAAE,SAAS,MAAM,EAXfA,EAAE,KACP,CACE,MAAO,qBACP,QAASG,EAAO,MAAM,QACtB,QAASA,EAAO,MAAM,OACxB,EACA,GACF,CAKJ,CAAC,EAGDL,EAAI,IAAI,QAAS,MAAOE,GAAM,CAE5B,GAAI,CADgBJ,EAAS,iBAAiB,EAE5C,OAAOI,EAAE,KACP,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,CAAI,MAClC,CACF,CAAC,CACH,CAAC,EAIDG,EAAI,IAAI,IAAK,MAAOE,GAAM,CAExB,GAAI,CADgBJ,EAAS,iBAAiB,EAE5C,OAAOI,EAAE,SAAS,EAGpB,IAAMI,EAAOJ,EAAE,IAAI,KAEnB,GAAI,CACF,IAAMK,EAAW,oBAAoBR,CAAc,GAAGO,CAAI,GACpDE,EAAM,IAAI,IAAIN,EAAE,IAAI,GAAG,EAEvBO,EAAU,IAAI,QACpBP,EAAE,IAAI,IAAI,QAAQ,QAAQ,CAACQ,EAAOC,IAAQ,CACpCA,EAAI,YAAY,IAAM,QACxBF,EAAQ,IAAIE,EAAKD,CAAK,CAE1B,CAAC,EAED,IAAME,EAAW,MAAM,MAAML,EAAWC,EAAI,OAAQ,CAClD,OAAQN,EAAE,IAAI,OACd,QAAAO,EACA,KAAM,CAAC,MAAO,MAAM,EAAE,SAASP,EAAE,IAAI,MAAM,EAAI,OAAY,MAAMA,EAAE,IAAI,YAAY,CACrF,CAAC,EAEKW,EAAkB,IAAI,QAC5B,OAAAD,EAAS,QAAQ,QAAQ,CAACF,EAAOC,IAAQ,CAClC,CAAC,oBAAqB,YAAY,EAAE,SAASA,EAAI,YAAY,CAAC,GACjEE,EAAgB,IAAIF,EAAKD,CAAK,CAElC,CAAC,EAEM,IAAI,SAASE,EAAS,KAAM,CACjC,OAAQA,EAAS,OACjB,WAAYA,EAAS,WACrB,QAASC,CACX,CAAC,CACH,MAAQ,CACN,OAAOX,EAAE,SAAS,CACpB,CACF,CAAC,EAGDc,EAAM,CACJ,MAAOhB,EAAI,MACX,KAAAH,CACF,CAAC,EAEDJ,EAAI,gDAA2CI,CAAI,KAAK,EACxDJ,EAAI,4BAA4BI,CAAI,gCAAgC,CACtE","names":["serve","Hono","log","loggers","startUIServer","options","port","duckpond","uiInternalPort","app","Hono","c","listResult","userId","result","path","proxyUrl","url","headers","value","key","response","responseHeaders","error","currentUser","serve"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as U}from"./chunk-
|
|
2
|
+
import{b as U}from"./chunk-JXCFUXVK.js";import"./chunk-R65UMTEX.js";import"./chunk-VSQCOL7H.js";import{a as _}from"./chunk-MPMUZFRC.js";import{b as D}from"./chunk-A3S6D44B.js";import{webcrypto as m}from"crypto";import{Command as O}from"commander";import{createRequire as d}from"module";globalThis.crypto||(globalThis.crypto=m);var v=d(import.meta.url),A=v("../package.json"),t=D.main;function P(){let e={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&&(e.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&&(e.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&&(e.s3.endpoint=process.env.DUCKPOND_S3_ENDPOINT)),e}var C=new O;C.name("duckpond-mcp-server").description("MCP server for multi-tenant DuckDB management with R2/S3 storage").version(A.version).option("-t, --transport <type>","Transport mode: stdio or http","stdio").option("-p, --port <port>","HTTP port (when using http transport)","3000").option("--ui","Enable DuckDB UI server (for stdio mode)").option("--ui-port <port>","UI server port (default: 4000)","4000").option("--ui-internal-port <port>","Internal DuckDB UI port (default: 4213)","4213").action(async e=>{try{let r=P(),n=_();t(`Starting DuckPond MCP Server with ${e.transport} transport`),t("Configuration:",{memoryLimit:r.memoryLimit,threads:r.threads,maxActiveUsers:r.maxActiveUsers,strategy:r.strategy,tempDir:r.tempDir,cacheDir:r.cacheDir,cacheType:r.cacheType,hasR2:!!r.r2,hasS3:!!r.s3,defaultUser:n||"(not set)"}),n&&console.error(`\u{1F464} Default user: ${n}`);let o;if(process.env.DUCKPOND_OAUTH_ENABLED==="true"){let a=process.env.DUCKPOND_OAUTH_USERNAME,p=process.env.DUCKPOND_OAUTH_PASSWORD;(!a||!p)&&(console.error("\u274C OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required"),process.exit(1)),o={enabled:!0,username:a,password:p,userId:process.env.DUCKPOND_OAUTH_USER_ID||a,email:process.env.DUCKPOND_OAUTH_EMAIL,issuer:process.env.DUCKPOND_OAUTH_ISSUER||`http://localhost:${parseInt(e.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}`));let c=e.ui||process.env.DUCKPOND_UI_ENABLED==="true",i=parseInt(e.uiPort)||4e3,u=parseInt(e.uiInternalPort)||4213;c&&e.transport==="stdio"&&console.error(`\u{1F5A5}\uFE0F UI server will be available at http://localhost:${i}/ui`),e.transport==="stdio"||e.transport==="http"?await U({config:r,port:parseInt(e.port)||3e3,endpoint:"/mcp",oauth:o,basicAuth:s,ui:c?{enabled:!0,port:i,internalPort:u}:void 0},e.transport==="stdio"?"stdio":"http"):(t(`Unknown transport: ${e.transport}`),process.exit(1))}catch(r){t("Fatal error:",r),console.error("Fatal error:",r),process.exit(1)}});C.parse();
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-JXCFUXVK.js";import"./chunk-R65UMTEX.js";import"./chunk-VSQCOL7H.js";import"./chunk-MPMUZFRC.js";import"./chunk-A3S6D44B.js";export{a as createFastMCPServer,b as startServer};
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/dist/ui-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-VSQCOL7H.js";import"./chunk-A3S6D44B.js";export{a as startUIServer};
|
|
2
2
|
//# sourceMappingURL=ui-server.js.map
|
package/package.json
CHANGED
package/dist/chunk-SIVPP6RP.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as I}from"./chunk-A3S6D44B.js";import{serve as f}from"@hono/node-server";import{Hono as m}from"hono";var c=I.core;async function w(p){let{port:s,duckpond:o}=p,h=o.getUIPort(),a=new m;a.get("/ui",r=>{if(!o.getCurrentUIUser()){let e=o.listUsers();return r.json({message:"No UI active. Visit /ui/:userId to start DuckDB UI for a user.",currentUser:null,availableUsers:e.success?e.data.users:[],endpoints:{startUI:`http://localhost:${s}/ui/:userId`}})}return r.redirect("/ui/")}),a.get("/ui/:userId",async r=>{let n=r.req.param("userId");c(`[UI Server] Starting UI for user: ${n}`);let e=await o.startUI(n);return e.success?r.redirect("/ui/"):r.json({error:"Failed to start UI",message:e.error.message,details:e.error.details},500)}),a.all("/ui/*",async r=>{if(!o.getCurrentUIUser())return r.json({error:"No UI active",message:"Start UI by visiting /ui/:userId first"},400);let e=r.req.path.replace(/^\/ui/,"")||"/";try{let t=`http://localhost:${h}${e}`,g=new URL(r.req.url),U=new Headers;r.req.raw.headers.forEach((d,i)=>{i.toLowerCase()!=="host"&&U.set(i,d)});let u=await fetch(t+g.search,{method:r.req.method,headers:U,body:["GET","HEAD"].includes(r.req.method)?void 0:await r.req.arrayBuffer()}),l=new Headers;return u.headers.forEach((d,i)=>{["transfer-encoding","connection"].includes(i.toLowerCase())||l.set(i,d)}),new Response(u.body,{status:u.status,statusText:u.statusText,headers:l})}catch(t){return c(`[UI Server] Proxy error: ${t instanceof Error?t.message:String(t)}`),r.json({error:"UI proxy error",message:t instanceof Error?t.message:"Failed to connect to DuckDB UI",hint:"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it."},502)}}),a.get("/",r=>{let n=o.getCurrentUIUser();return r.json({name:"DuckPond UI Server",description:"Lightweight HTTP server for DuckDB UI access in stdio mode",currentUIUser:n,endpoints:{ui:`http://localhost:${s}/ui/:userId`,uiRoot:`http://localhost:${s}/ui/`}})}),f({fetch:a.fetch,port:s}),c(`\u2713 UI server running at http://localhost:${s}/ui`),c(` Visit http://localhost:${s}/ui/:userId to start DuckDB UI`)}export{w as a};
|
|
2
|
-
//# sourceMappingURL=chunk-SIVPP6RP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ui-server.ts"],"sourcesContent":["import { serve } from \"@hono/node-server\"\nimport { Hono } from \"hono\"\n\nimport type { DuckPondServer } from \"./server-core\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.core\n\nexport type UIServerOptions = {\n port: number\n duckpond: DuckPondServer\n}\n\n/**\n * Start a lightweight HTTP server for UI access in stdio mode\n * This allows accessing DuckDB UI even when MCP is running over stdio\n */\nexport async function startUIServer(options: UIServerOptions): Promise<void> {\n const { port, duckpond } = options\n const uiInternalPort = duckpond.getUIPort()\n\n const app = new Hono()\n\n // GET /ui - Info endpoint when no UI running, or redirect to UI\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n const listResult = duckpond.listUsers()\n return c.json({\n message: \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser: null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `http://localhost:${port}/ui/:userId`,\n },\n })\n }\n // Redirect to the UI root\n return c.redirect(\"/ui/\")\n })\n\n // GET /ui/:userId - Start UI for a specific user and redirect\n app.get(\"/ui/:userId\", async (c) => {\n const userId = c.req.param(\"userId\")\n\n log(`[UI Server] Starting UI for user: ${userId}`)\n const result = await duckpond.startUI(userId)\n\n if (!result.success) {\n return c.json(\n {\n error: \"Failed to start UI\",\n message: result.error.message,\n details: result.error.details,\n },\n 500,\n )\n }\n\n // Redirect to the UI\n return c.redirect(\"/ui/\")\n })\n\n // ALL /ui/* - Proxy requests to DuckDB UI server\n app.all(\"/ui/*\", async (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n if (!currentUser) {\n return c.json(\n {\n error: \"No UI active\",\n message: \"Start UI by visiting /ui/:userId first\",\n },\n 400,\n )\n }\n\n // Get the path after /ui\n const path = c.req.path.replace(/^\\/ui/, \"\") || \"/\"\n\n try {\n // Build the proxy URL\n const proxyUrl = `http://localhost:${uiInternalPort}${path}`\n const url = new URL(c.req.url)\n\n // Prepare headers, filtering out host\n const headers = new Headers()\n c.req.raw.headers.forEach((value, key) => {\n if (key.toLowerCase() !== \"host\") {\n headers.set(key, value)\n }\n })\n\n // Make the proxy request\n const response = await fetch(proxyUrl + url.search, {\n method: c.req.method,\n headers,\n body: [\"GET\", \"HEAD\"].includes(c.req.method) ? undefined : await c.req.arrayBuffer(),\n })\n\n // Return the proxied response\n const responseHeaders = new Headers()\n response.headers.forEach((value, key) => {\n // Don't forward certain headers\n if (![\"transfer-encoding\", \"connection\"].includes(key.toLowerCase())) {\n responseHeaders.set(key, value)\n }\n })\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n })\n } catch (error) {\n log(`[UI Server] Proxy error: ${error instanceof Error ? error.message : String(error)}`)\n return c.json(\n {\n error: \"UI proxy error\",\n message: error instanceof Error ? error.message : \"Failed to connect to DuckDB UI\",\n hint: \"The DuckDB UI server may not be running. Try visiting /ui/:userId to restart it.\",\n },\n 502,\n )\n }\n })\n\n // Root endpoint with info\n app.get(\"/\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n return c.json({\n name: \"DuckPond UI Server\",\n description: \"Lightweight HTTP server for DuckDB UI access in stdio mode\",\n currentUIUser: currentUser,\n endpoints: {\n ui: `http://localhost:${port}/ui/:userId`,\n uiRoot: `http://localhost:${port}/ui/`,\n },\n })\n })\n\n // Start the server\n serve({\n fetch: app.fetch,\n port,\n })\n\n log(`✓ UI server running at http://localhost:${port}/ui`)\n log(` Visit http://localhost:${port}/ui/:userId to start DuckDB UI`)\n}\n"],"mappings":"wCAAA,OAAS,SAAAA,MAAa,oBACtB,OAAS,QAAAC,MAAY,OAKrB,IAAMC,EAAMC,EAAQ,KAWpB,eAAsBC,EAAcC,EAAyC,CAC3E,GAAM,CAAE,KAAAC,EAAM,SAAAC,CAAS,EAAIF,EACrBG,EAAiBD,EAAS,UAAU,EAEpCE,EAAM,IAAIC,EAGhBD,EAAI,IAAI,MAAQE,GAAM,CAEpB,GAAI,CADgBJ,EAAS,iBAAiB,EAC5B,CAChB,IAAMK,EAAaL,EAAS,UAAU,EACtC,OAAOI,EAAE,KAAK,CACZ,QAAS,iEACT,YAAa,KACb,eAAgBC,EAAW,QAAUA,EAAW,KAAK,MAAQ,CAAC,EAC9D,UAAW,CACT,QAAS,oBAAoBN,CAAI,aACnC,CACF,CAAC,CACH,CAEA,OAAOK,EAAE,SAAS,MAAM,CAC1B,CAAC,EA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CACX,CAAC,CACH,OAASC,EAAO,CACd,OAAArB,EAAI,4BAA4BqB,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,EACjFZ,EAAE,KACP,CACE,MAAO,iBACP,QAASY,aAAiB,MAAQA,EAAM,QAAU,iCAClD,KAAM,kFACR,EACA,GACF,CACF,CACF,CAAC,EAGDd,EAAI,IAAI,IAAME,GAAM,CAClB,IAAMa,EAAcjB,EAAS,iBAAiB,EAC9C,OAAOI,EAAE,KAAK,CACZ,KAAM,qBACN,YAAa,6DACb,cAAea,EACf,UAAW,CACT,GAAI,oBAAoBlB,CAAI,cAC5B,OAAQ,oBAAoBA,CAAI,MAClC,CACF,CAAC,CACH,CAAC,EAGDmB,EAAM,CACJ,MAAOhB,EAAI,MACX,KAAAH,CACF,CAAC,EAEDJ,EAAI,gDAA2CI,CAAI,KAAK,EACxDJ,EAAI,4BAA4BI,CAAI,gCAAgC,CACtE","names":["serve","Hono","log","loggers","startUIServer","options","port","duckpond","uiInternalPort","app","Hono","c","listResult","userId","result","path","proxyUrl","url","headers","value","key","response","responseHeaders","error","currentUser","serve"]}
|