duckpond-mcp-server 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,7 @@ Built on top of the [duckpond](https://github.com/jordanburke/duckpond) library,
14
14
  - 🔌 **Dual Transport** - stdio (Claude Desktop) and HTTP (server deployments)
15
15
  - 🔐 **Authentication** - OAuth 2.0 and Basic Auth support for HTTP
16
16
  - 🎯 **MCP Tools** - Query, execute, stats, cache management
17
+ - 🖥️ **DuckDB UI** - Built-in web UI for database inspection and debugging
17
18
  - 📊 **Type Safe** - Full TypeScript with functype error handling
18
19
 
19
20
  ## Quick Start
@@ -268,6 +269,92 @@ npx duckpond-mcp-server --transport http
268
269
  - `GET /oauth/jwks` - JSON Web Key Set
269
270
  - `POST /oauth/register` - Client registration
270
271
 
272
+ ### DuckDB UI
273
+
274
+ - `GET /ui` - UI status and available users
275
+ - `GET /ui/:userId` - Start UI for specific user
276
+ - `GET /ui/*` - Proxy to DuckDB UI server
277
+
278
+ ## DuckDB UI
279
+
280
+ The MCP server includes built-in support for [DuckDB UI](https://duckdb.org/docs/stable/core_extensions/ui.html), allowing you to visually inspect and debug any user's database through a web browser.
281
+
282
+ ### HTTP Mode (default)
283
+
284
+ When running in HTTP mode, the UI is automatically available:
285
+
286
+ ```bash
287
+ # Start server
288
+ npx duckpond-mcp-server --transport http --port 3000
289
+
290
+ # Open UI for user "claude"
291
+ # Browser: http://localhost:3000/ui/claude
292
+ ```
293
+
294
+ ### stdio Mode
295
+
296
+ For stdio mode (Claude Desktop), enable the UI server with the `--ui` flag:
297
+
298
+ ```bash
299
+ # Start with UI enabled
300
+ npx duckpond-mcp-server --transport stdio --ui --ui-port 4000
301
+
302
+ # MCP communicates via stdin/stdout
303
+ # UI available at: http://localhost:4000/ui/claude
304
+ ```
305
+
306
+ ### Claude Desktop with UI
307
+
308
+ Add UI support to your Claude Desktop config:
309
+
310
+ ```json
311
+ {
312
+ "mcpServers": {
313
+ "duckpond": {
314
+ "command": "npx",
315
+ "args": ["-y", "duckpond-mcp-server", "--ui", "--ui-port", "4000"],
316
+ "env": {
317
+ "DUCKPOND_DEFAULT_USER": "claude"
318
+ }
319
+ }
320
+ }
321
+ }
322
+ ```
323
+
324
+ Then browse to `http://localhost:4000/ui/claude` to inspect the database.
325
+
326
+ ### Docker
327
+
328
+ ```bash
329
+ # Run with port mapping
330
+ docker run -p 3000:3000 duckpond-mcp-server
331
+
332
+ # Access UI
333
+ # Browser: http://localhost:3000/ui/claude
334
+ ```
335
+
336
+ ### UI Features
337
+
338
+ - **Database Explorer** - Browse schemas, tables, and columns
339
+ - **SQL Notebooks** - Execute queries with syntax highlighting
340
+ - **Table Summaries** - Row counts, data profiles, previews
341
+ - **Column Explorer** - Detailed column statistics and insights
342
+
343
+ ### Switching Users
344
+
345
+ Navigate to `/ui/:differentUserId` to switch between users. Only one user's UI is active at a time - switching automatically stops the previous UI and starts for the new user.
346
+
347
+ ### Environment Variables
348
+
349
+ - `DUCKPOND_UI_ENABLED` - Enable UI in stdio mode (default: `false`)
350
+ - `DUCKPOND_UI_PORT` - UI server port for stdio mode (default: `4000`)
351
+
352
+ ### CLI Flags
353
+
354
+ - `--ui` - Enable UI server in stdio mode
355
+ - `--ui-port <port>` - UI server port (default: `4000`)
356
+ - `--ui-internal-port <port>` - Internal DuckDB UI port (default: `4213`)
357
+
271
358
  ## Development
272
359
 
273
360
  ### Local Development
@@ -0,0 +1,2 @@
1
+ import{b as i}from"./chunk-A3S6D44B.js";import{z as o}from"zod";var n=i.tools;function u(){return process.env.DUCKPOND_DEFAULT_USER}function c(r){let s=r||u();if(!s)throw new Error("userId is required. Either provide it in the request or set DUCKPOND_DEFAULT_USER environment variable.");return s}var l=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)"),sql:o.string().min(1).describe("SQL query to execute")}),f=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)"),sql:o.string().min(1).describe("SQL statement to execute (DDL/DML)")}),U=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),S=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),m=o.object({userId:o.string().min(1).optional().describe("User identifier (optional if DUCKPOND_DEFAULT_USER is set)")}),p=o.object({}),g={async query(r,s){let t=c(s.userId);n(`Tool: query for user ${t}`);let e=await r.query(t,s.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2)}]}},async execute(r,s){let t=c(s.userId);n(`Tool: execute for user ${t}`);let e=await r.execute(t,s.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2)}]}},async getUserStats(r,s){let t=c(s.userId);n(`Tool: getUserStats for user ${t}`);let e=await r.getUserStats(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2)}]}},isAttached(r,s){let t=c(s.userId);n(`Tool: isAttached for user ${t}`);let e=r.isAttached(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({attached:e.data,userId:t},null,2)}]}},async detachUser(r,s){let t=c(s.userId);n(`Tool: detachUser for user ${t}`);let e=await r.detachUser(t);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:`User ${t} detached successfully`},null,2)}]}},listUsers(r,s){n("Tool: listUsers");let t=r.listUsers();if(!t.success)throw new Error(t.error.message);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}]}}};export{u as a,c as b,l as c,f as d,U as e,S as f,m as g,p as h,g as i};
2
+ //# sourceMappingURL=chunk-MPMUZFRC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\nimport type { DuckPondServer } from \"../server-core\"\nimport { loggers } from \"../utils/logger\"\n\nconst log = loggers.tools\n\n/**\n * Get the default user ID from environment variable\n */\nexport function getDefaultUserId(): string | undefined {\n return process.env.DUCKPOND_DEFAULT_USER\n}\n\n/**\n * Resolve user ID from input or default\n * @throws Error if no user ID is available\n */\nexport function resolveUserId(inputUserId?: string): string {\n const userId = inputUserId || getDefaultUserId()\n if (!userId) {\n throw new Error(\n \"userId is required. Either provide it in the request or set DUCKPOND_DEFAULT_USER environment variable.\",\n )\n }\n return userId\n}\n\n/**\n * Zod schema for query tool\n */\nexport const querySchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n sql: z.string().min(1).describe(\"SQL query to execute\"),\n})\n\n/**\n * Zod schema for execute tool\n */\nexport const executeSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n sql: z.string().min(1).describe(\"SQL statement to execute (DDL/DML)\"),\n})\n\n/**\n * Zod schema for getUserStats tool\n */\nexport const getUserStatsSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for isAttached tool\n */\nexport const isAttachedSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for detachUser tool\n */\nexport const detachUserSchema = z.object({\n userId: z.string().min(1).optional().describe(\"User identifier (optional if DUCKPOND_DEFAULT_USER is set)\"),\n})\n\n/**\n * Zod schema for listUsers tool\n */\nexport const listUsersSchema = z.object({})\n\n/**\n * Tool implementations for MCP server\n */\nexport const tools = {\n /**\n * Execute a SQL query for a user\n */\n async query(server: DuckPondServer, input: z.infer<typeof querySchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: query for user ${userId}`)\n const result = await server.query(userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Execute DDL/DML statement\n */\n async execute(server: DuckPondServer, input: z.infer<typeof executeSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: execute for user ${userId}`)\n const result = await server.execute(userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Get user database statistics\n */\n async getUserStats(server: DuckPondServer, input: z.infer<typeof getUserStatsSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: getUserStats for user ${userId}`)\n const result = await server.getUserStats(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Check if user is attached\n */\n isAttached(server: DuckPondServer, input: z.infer<typeof isAttachedSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: isAttached for user ${userId}`)\n const result = server.isAttached(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n attached: result.data,\n userId,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Detach a user from cache\n */\n async detachUser(server: DuckPondServer, input: z.infer<typeof detachUserSchema>) {\n const userId = resolveUserId(input.userId)\n log(`Tool: detachUser for user ${userId}`)\n const result = await server.detachUser(userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: `User ${userId} detached successfully`,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * List all currently cached users\n */\n listUsers(server: DuckPondServer, _input: z.infer<typeof listUsersSchema>) {\n log(\"Tool: listUsers\")\n const result = server.listUsers()\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n }\n },\n}\n"],"mappings":"wCAAA,OAAS,KAAAA,MAAS,MAKlB,IAAMC,EAAMC,EAAQ,MAKb,SAASC,GAAuC,CACrD,OAAO,QAAQ,IAAI,qBACrB,CAMO,SAASC,EAAcC,EAA8B,CAC1D,IAAMC,EAASD,GAAeF,EAAiB,EAC/C,GAAI,CAACG,EACH,MAAM,IAAI,MACR,yGACF,EAEF,OAAOA,CACT,CAKO,IAAMC,EAAcC,EAAE,OAAO,CAClC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,4DAA4D,EAC1G,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,sBAAsB,CACxD,CAAC,EAKYC,EAAgBD,EAAE,OAAO,CACpC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,4DAA4D,EAC1G,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,oCAAoC,CACtE,CAAC,EAKYE,EAAqBF,EAAE,OAAO,CACzC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,4DAA4D,CAC5G,CAAC,EAKYG,EAAmBH,EAAE,OAAO,CACvC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,4DAA4D,CAC5G,CAAC,EAKYI,EAAmBJ,EAAE,OAAO,CACvC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,E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CACF,CACF,CACF,CACF,EAKA,WAAWF,EAAwBC,EAAyC,CAC1E,IAAMV,EAASF,EAAcY,EAAM,MAAM,EACzCf,EAAI,6BAA6BK,CAAM,EAAE,EACzC,IAAMW,EAASF,EAAO,WAAWT,CAAM,EAEvC,GAAI,CAACW,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,SAAUA,EAAO,KACjB,OAAAX,CACF,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,MAAM,WAAWS,EAAwBC,EAAyC,CAChF,IAAMV,EAASF,EAAcY,EAAM,MAAM,EACzCf,EAAI,6BAA6BK,CAAM,EAAE,EACzC,IAAMW,EAAS,MAAMF,EAAO,WAAWT,CAAM,EAE7C,GAAI,CAACW,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,QAAS,GACT,QAAS,QAAQX,CAAM,wBACzB,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,UAAUS,EAAwBG,EAAyC,CACzEjB,EAAI,iBAAiB,EACrB,IAAMgB,EAASF,EAAO,UAAU,EAEhC,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UAAUA,EAAO,KAAM,KAAM,CAAC,CAC3C,CACF,CACF,CACF,CACF","names":["z","log","loggers","getDefaultUserId","resolveUserId","inputUserId","userId","querySchema","z","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","tools","server","input","result","_input"]}
@@ -0,0 +1,2 @@
1
+ import{a as n,b as a}from"./chunk-A3S6D44B.js";import{DuckPond as c}from"duckpond";var s=a.core,u=class{constructor(t){this.config=t;n(this,"pond",null);n(this,"initialized",!1);n(this,"currentUIUserId",null);n(this,"uiInternalPort",4213);s("DuckPondServer created")}async init(){if(this.initialized)return s("Already initialized"),{success:!0,data:void 0};s("Initializing DuckPond...");let t=Date.now();this.pond=new c(this.config);let e=await this.pond.init();return this.handleEither(e,Date.now()-t)}async query(t,e){if(!this.pond)return this.notInitializedError();s(`Query for user ${t}: ${e.substring(0,100)}...`);let r=Date.now(),i=await this.pond.query(t,e);return this.handleEither(i,Date.now()-r)}async execute(t,e){if(!this.pond)return this.notInitializedError();s(`Execute for user ${t}: ${e.substring(0,100)}...`);let r=Date.now(),i=await this.pond.execute(t,e);return this.handleEither(i,Date.now()-r)}async getUserStats(t){if(!this.pond)return this.notInitializedError();s(`Getting stats for user ${t}`);let e=Date.now(),r=await this.pond.getUserStats(t);return this.handleEither(r,Date.now()-e)}isAttached(t){if(!this.pond)return this.notInitializedError();let e=this.pond.isAttached(t);return s(`User ${t} attached: ${e}`),{success:!0,data:e}}async detachUser(t){if(!this.pond)return this.notInitializedError();s(`Detaching user ${t}`);let e=Date.now(),r=await this.pond.detachUser(t);return this.handleEither(r,Date.now()-e)}listUsers(){if(!this.pond)return this.notInitializedError();s("Listing cached users");let t=this.pond.listUsers();return{success:!0,data:{users:t.users.toArray(),count:t.count,maxActiveUsers:t.maxActiveUsers,utilizationPercent:t.utilizationPercent}}}async close(){if(!this.pond)return{success:!0,data:void 0};s("Closing DuckPond...");let t=Date.now();this.currentUIUserId&&await this.stopUI();let e=await this.pond.close();return this.initialized=!1,this.pond=null,this.handleEither(e,Date.now()-t)}async startUI(t){if(!this.pond)return this.notInitializedError();s(`Starting UI for user ${t}`);let e=Date.now();if(this.currentUIUserId&&this.currentUIUserId!==t&&(s(`Stopping UI for previous user ${this.currentUIUserId}`),await this.stopUI()),this.currentUIUserId===t)return s(`UI already running for user ${t}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-e};let r=await this.execute(t,"INSTALL ui; LOAD ui;");if(!r.success)return s(`Failed to install UI extension: ${r.error.message}`),r;let i=await this.execute(t,`SET ui_local_port = ${this.uiInternalPort}`);if(!i.success)return s(`Failed to set UI port: ${i.error.message}`),i;let o=await this.execute(t,"CALL start_ui_server()");return o.success?(this.currentUIUserId=t,s(`UI started for user ${t} on port ${this.uiInternalPort}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-e}):(s(`Failed to start UI server: ${o.error.message}`),o)}async stopUI(){if(!this.currentUIUserId)return s("No UI running to stop"),{success:!0,data:void 0};if(!this.pond)return this.currentUIUserId=null,{success:!0,data:void 0};s(`Stopping UI for user ${this.currentUIUserId}`);let t=Date.now(),e=await this.execute(this.currentUIUserId,"CALL stop_ui_server()"),r=this.currentUIUserId;return this.currentUIUserId=null,e.success?(s(`UI stopped for user ${r}`),{success:!0,data:void 0,executionTime:Date.now()-t}):(s(`Failed to stop UI: ${e.error.message}`),e)}getCurrentUIUser(){return this.currentUIUserId}setUIPort(t){this.uiInternalPort=t}getUIPort(){return this.uiInternalPort}handleEither(t,e){return t.fold(r=>({success:!1,error:{code:this.mapErrorCode(r.code),message:r.message,details:{originalCode:r.code,context:r.context,cause:r.cause?.message}}}),r=>({success:!0,data:r,executionTime:e}))}mapErrorCode(t){return{CONNECTION_FAILED:"SERVICE_UNAVAILABLE",CONNECTION_TIMEOUT:"TIMEOUT",R2_CONNECTION_ERROR:"SERVICE_UNAVAILABLE",S3_CONNECTION_ERROR:"SERVICE_UNAVAILABLE",USER_NOT_FOUND:"NOT_FOUND",USER_ALREADY_EXISTS:"ALREADY_EXISTS",USER_NOT_ATTACHED:"NOT_FOUND",QUERY_EXECUTION_ERROR:"INVALID_REQUEST",QUERY_TIMEOUT:"TIMEOUT",INVALID_SQL:"INVALID_REQUEST",MEMORY_LIMIT_EXCEEDED:"RESOURCE_EXHAUSTED",STORAGE_ERROR:"SERVICE_UNAVAILABLE",STORAGE_QUOTA_EXCEEDED:"RESOURCE_EXHAUSTED",INVALID_CONFIG:"INVALID_ARGUMENT",NOT_INITIALIZED:"FAILED_PRECONDITION",UNKNOWN_ERROR:"INTERNAL_ERROR"}[t]||"INTERNAL_ERROR"}notInitializedError(){return{success:!1,error:{code:"FAILED_PRECONDITION",message:"DuckPond not initialized. Call init() first."}}}};export{u as a};
2
+ //# sourceMappingURL=chunk-R65UMTEX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server-core.ts"],"sourcesContent":["import type { Either } from \"duckpond\"\nimport { DuckPond, type DuckPondConfig, type ErrorCode, type ListUsersResult, type UserStats } from \"duckpond\"\n\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.core\n\n/**\n * Result type for MCP tool responses\n */\nexport type MCPResult<T> =\n | {\n success: true\n data: T\n executionTime?: number\n }\n | {\n success: false\n error: {\n code: string\n message: string\n details?: {\n originalCode?: ErrorCode\n context?: Record<string, unknown>\n cause?: string\n }\n }\n }\n\n/**\n * Configuration for DuckPond MCP Server\n * Currently identical to DuckPondConfig, but can be extended with server-specific options\n */\nexport type DuckPondServerConfig = DuckPondConfig\n\n/**\n * Core DuckPond MCP Server\n *\n * Wraps DuckPond library with MCP-compatible result types\n */\nexport class DuckPondServer {\n private pond: DuckPond | null = null\n private initialized = false\n private currentUIUserId: string | null = null\n private uiInternalPort: number = 4213\n\n constructor(private config: DuckPondServerConfig) {\n log(\"DuckPondServer created\")\n }\n\n /**\n * Initialize the DuckPond instance\n */\n async init(): Promise<MCPResult<void>> {\n if (this.initialized) {\n log(\"Already initialized\")\n return { success: true, data: undefined }\n }\n\n log(\"Initializing DuckPond...\")\n const startTime = Date.now()\n\n this.pond = new DuckPond(this.config)\n const result = await this.pond.init()\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Execute a SQL query for a user\n */\n async query<T = unknown>(userId: string, sql: string): Promise<MCPResult<T[]>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Query for user ${userId}: ${sql.substring(0, 100)}...`)\n const startTime = Date.now()\n\n const result = await this.pond.query<T>(userId, sql)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Execute DDL/DML without returning results\n */\n async execute(userId: string, sql: string): Promise<MCPResult<void>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Execute for user ${userId}: ${sql.substring(0, 100)}...`)\n const startTime = Date.now()\n\n const result = await this.pond.execute(userId, sql)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Get statistics about a user's database\n */\n async getUserStats(userId: string): Promise<MCPResult<UserStats>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Getting stats for user ${userId}`)\n const startTime = Date.now()\n\n const result = await this.pond.getUserStats(userId)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Check if a user is currently cached\n */\n isAttached(userId: string): MCPResult<boolean> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n const attached = this.pond.isAttached(userId)\n log(`User ${userId} attached: ${attached}`)\n\n return {\n success: true,\n data: attached,\n }\n }\n\n /**\n * Manually detach a user from the cache\n */\n async detachUser(userId: string): Promise<MCPResult<void>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Detaching user ${userId}`)\n const startTime = Date.now()\n\n const result = await this.pond.detachUser(userId)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * List all currently cached users\n */\n listUsers(): MCPResult<{ users: string[]; count: number; maxActiveUsers: number; utilizationPercent: number }> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(\"Listing cached users\")\n const result = this.pond.listUsers()\n\n return {\n success: true,\n data: {\n users: result.users.toArray(), // Convert List<string> to string[]\n count: result.count,\n maxActiveUsers: result.maxActiveUsers,\n utilizationPercent: result.utilizationPercent,\n },\n }\n }\n\n /**\n * Close the DuckPond instance\n */\n async close(): Promise<MCPResult<void>> {\n if (!this.pond) {\n return { success: true, data: undefined }\n }\n\n log(\"Closing DuckPond...\")\n const startTime = Date.now()\n\n // Stop UI server if running\n if (this.currentUIUserId) {\n await this.stopUI()\n }\n\n const result = await this.pond.close()\n this.initialized = false\n this.pond = null\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Start DuckDB UI for a specific user\n * Only one user's UI can be active at a time\n */\n async startUI(userId: string): Promise<MCPResult<{ port: number }>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Starting UI for user ${userId}`)\n const startTime = Date.now()\n\n // Stop existing UI if different user\n if (this.currentUIUserId && this.currentUIUserId !== userId) {\n log(`Stopping UI for previous user ${this.currentUIUserId}`)\n await this.stopUI()\n }\n\n // If already running for this user, just return success\n if (this.currentUIUserId === userId) {\n log(`UI already running for user ${userId}`)\n return {\n success: true,\n data: { port: this.uiInternalPort },\n executionTime: Date.now() - startTime,\n }\n }\n\n // Install and load UI extension\n const installResult = await this.execute(userId, \"INSTALL ui; LOAD ui;\")\n if (!installResult.success) {\n log(`Failed to install UI extension: ${installResult.error.message}`)\n return installResult as MCPResult<{ port: number }>\n }\n\n // Set the UI port\n const portResult = await this.execute(userId, `SET ui_local_port = ${this.uiInternalPort}`)\n if (!portResult.success) {\n log(`Failed to set UI port: ${portResult.error.message}`)\n return portResult as MCPResult<{ port: number }>\n }\n\n // Start the UI server (without opening browser)\n const startResult = await this.execute(userId, \"CALL start_ui_server()\")\n if (!startResult.success) {\n log(`Failed to start UI server: ${startResult.error.message}`)\n return startResult as MCPResult<{ port: number }>\n }\n\n this.currentUIUserId = userId\n log(`UI started for user ${userId} on port ${this.uiInternalPort}`)\n\n return {\n success: true,\n data: { port: this.uiInternalPort },\n executionTime: Date.now() - startTime,\n }\n }\n\n /**\n * Stop the currently running DuckDB UI\n */\n async stopUI(): Promise<MCPResult<void>> {\n if (!this.currentUIUserId) {\n log(\"No UI running to stop\")\n return { success: true, data: undefined }\n }\n\n if (!this.pond) {\n this.currentUIUserId = null\n return { success: true, data: undefined }\n }\n\n log(`Stopping UI for user ${this.currentUIUserId}`)\n const startTime = Date.now()\n\n const result = await this.execute(this.currentUIUserId, \"CALL stop_ui_server()\")\n const previousUser = this.currentUIUserId\n this.currentUIUserId = null\n\n if (result.success) {\n log(`UI stopped for user ${previousUser}`)\n return {\n success: true,\n data: undefined,\n executionTime: Date.now() - startTime,\n }\n }\n\n log(`Failed to stop UI: ${result.error.message}`)\n return result\n }\n\n /**\n * Get the user ID for the currently running UI\n */\n getCurrentUIUser(): string | null {\n return this.currentUIUserId\n }\n\n /**\n * Set the internal port for DuckDB UI\n */\n setUIPort(port: number): void {\n this.uiInternalPort = port\n }\n\n /**\n * Get the internal port for DuckDB UI\n */\n getUIPort(): number {\n return this.uiInternalPort\n }\n\n /**\n * Convert Either<Error, T> to MCPResult<T>\n */\n private handleEither<T>(\n result: Either<{ code: ErrorCode; message: string; cause?: Error; context?: Record<string, unknown> }, T>,\n executionTime: number,\n ): MCPResult<T> {\n return result.fold(\n (error) => ({\n success: false,\n error: {\n code: this.mapErrorCode(error.code),\n message: error.message,\n details: {\n originalCode: error.code,\n context: error.context,\n cause: error.cause?.message,\n },\n },\n }),\n (data) => ({\n success: true,\n data,\n executionTime,\n }),\n )\n }\n\n /**\n * Map DuckPond ErrorCode to MCP error code\n */\n private mapErrorCode(code: ErrorCode): string {\n const mapping: Record<ErrorCode, string> = {\n CONNECTION_FAILED: \"SERVICE_UNAVAILABLE\",\n CONNECTION_TIMEOUT: \"TIMEOUT\",\n R2_CONNECTION_ERROR: \"SERVICE_UNAVAILABLE\",\n S3_CONNECTION_ERROR: \"SERVICE_UNAVAILABLE\",\n USER_NOT_FOUND: \"NOT_FOUND\",\n USER_ALREADY_EXISTS: \"ALREADY_EXISTS\",\n USER_NOT_ATTACHED: \"NOT_FOUND\",\n QUERY_EXECUTION_ERROR: \"INVALID_REQUEST\",\n QUERY_TIMEOUT: \"TIMEOUT\",\n INVALID_SQL: \"INVALID_REQUEST\",\n MEMORY_LIMIT_EXCEEDED: \"RESOURCE_EXHAUSTED\",\n STORAGE_ERROR: \"SERVICE_UNAVAILABLE\",\n STORAGE_QUOTA_EXCEEDED: \"RESOURCE_EXHAUSTED\",\n INVALID_CONFIG: \"INVALID_ARGUMENT\",\n NOT_INITIALIZED: \"FAILED_PRECONDITION\",\n UNKNOWN_ERROR: \"INTERNAL_ERROR\",\n }\n\n return mapping[code] || \"INTERNAL_ERROR\"\n }\n\n /**\n * Helper for not initialized error\n */\n private notInitializedError<T>(): MCPResult<T> {\n return {\n success: false,\n error: {\n code: \"FAILED_PRECONDITION\",\n message: \"DuckPond not initialized. Call init() first.\",\n },\n }\n }\n}\n"],"mappings":"+CACA,OAAS,YAAAA,MAA2F,WAIpG,IAAMC,EAAMC,EAAQ,KAmCPC,EAAN,KAAqB,CAM1B,YAAoBC,EAA8B,CAA9B,YAAAA,EALpBC,EAAA,KAAQ,OAAwB,MAChCA,EAAA,KAAQ,cAAc,IACtBA,EAAA,KAAQ,kBAAiC,MACzCA,EAAA,KAAQ,iBAAyB,MAG/BJ,EAAI,wBAAwB,CAC9B,CAKA,MAAM,MAAiC,CACrC,GAAI,KAAK,YACP,OAAAA,EAAI,qBAAqB,EAClB,CAAE,QAAS,GAAM,KAAM,MAAU,EAG1CA,EAAI,0BAA0B,EAC9B,IAAMK,EAAY,KAAK,IAAI,EAE3B,KAAK,KAAO,IAAIC,EAAS,KAAK,MAAM,EACpC,IAAMC,EAAS,MAAM,KAAK,KAAK,KAAK,EAEpC,OAAO,KAAK,aAAaA,EAAQ,KAAK,IAAI,EAAIF,CAAS,CACzD,CAKA,MAAM,MAAmBG,EAAgBC,EAAsC,CAC7E,GAAI,CAAC,KAAK,KACR,OAAO,KAAK,oBAAoB,EAGlCT,EAAI,kBAAkBQ,CAAM,KAAKC,EAAI,UAAU,EAAG,GAAG,CAAC,KAAK,EAC3D,IAAMJ,EAAY,KAAK,IAAI,EAErBE,EAAS,MAAM,KAAK,KAAK,MAASC,EAAQC,CAAG,EAEnD,OAAO,KAAK,aAAaF,EAAQ,KAAK,IAAI,EAAIF,CAAS,CACzD,CAKA,MAAM,QAAQG,EAAgBC,EAAuC,CACnE,GAAI,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ACb,sBAAuB,qBACvB,cAAe,sBACf,uBAAwB,qBACxB,eAAgB,mBAChB,gBAAiB,sBACjB,cAAe,gBACjB,EAEeA,CAAI,GAAK,gBAC1B,CAKQ,qBAAuC,CAC7C,MAAO,CACL,QAAS,GACT,MAAO,CACL,KAAM,sBACN,QAAS,8CACX,CACF,CACF,CACF","names":["DuckPond","log","loggers","DuckPondServer","config","__publicField","startTime","DuckPond","result","userId","sql","attached","installResult","portResult","startResult","previousUser","port","executionTime","error","data","code"]}
@@ -0,0 +1,2 @@
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
@@ -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 // 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,CACE,MAAO,eACP,QAAS,wCACX,EACA,GACF,EAIF,IAAMI,EAAOJ,EAAE,IAAI,KAAK,QAAQ,QAAS,EAAE,GAAK,IAEhD,GAAI,CAEF,IAAM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K,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"]}
@@ -0,0 +1,48 @@
1
+ import{a as A}from"./chunk-R65UMTEX.js";import{a as E}from"./chunk-SIVPP6RP.js";import{b as y,c as U,d as C,e as O,f as $,g as T,h as P}from"./chunk-MPMUZFRC.js";import{b as R}from"./chunk-A3S6D44B.js";import{webcrypto as z}from"crypto";import{FastMCP as D}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 M}from"url";globalThis.crypto||(globalThis.crypto=z);var W=J(import.meta.url),I=W("../package.json"),u=R.fastmcp,x=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 F(s){u("\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 D({...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:r=>{let e=r.headers?.authorization,t=s.oauth?.issuer||`http://localhost:${s.port||3e3}`;if(!e)throw s.oauth?.enabled?new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required. Please authenticate via OAuth."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${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&&e.startsWith("Basic ")){let c=Buffer.from(e.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&&e.startsWith("Bearer ")){let c=e.slice(7);try{let i=S.verify(c,x);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 D(h);o.addTool({name:"query",description:"Execute a SQL query for a specific user and return results",parameters:U,execute:async r=>{try{let e=y(r.userId),t=await a.query(e,r.sql);return t.success?JSON.stringify({rows:t.data,rowCount:t.data.length,executionTime:t.executionTime},null,2):`ERROR: ${t.error.message}`}catch(e){u("Error in query tool:",e);let t=e instanceof Error?e.message:String(e);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:C,execute:async r=>{try{let e=y(r.userId),t=await a.execute(e,r.sql);return t.success?JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:t.executionTime},null,2):`ERROR: ${t.error.message}`}catch(e){u("Error in execute tool:",e);let t=e instanceof Error?e.message:String(e);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:O,execute:async r=>{try{let e=y(r.userId),t=await a.getUserStats(e);return t.success?JSON.stringify({...t.data,lastAccess:t.data.lastAccess.toISOString()},null,2):`ERROR: ${t.error.message}`}catch(e){u("Error in getUserStats tool:",e);let t=e instanceof Error?e.message:String(e);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:$,execute:async r=>{try{let e=y(r.userId),t=a.isAttached(e);return t.success?JSON.stringify({attached:t.data,userId:e},null,2):`ERROR: ${t.error.message}`}catch(e){u("Error in isAttached tool:",e);let t=e instanceof Error?e.message:String(e);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:T,execute:async r=>{try{let e=y(r.userId),t=await a.detachUser(e);return t.success?JSON.stringify({success:!0,message:`User ${e} detached successfully`},null,2):`ERROR: ${t.error.message}`}catch(e){u("Error in detachUser tool:",e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),o.addTool({name:"listUsers",description:"List all currently cached users and cache statistics",parameters:P,execute:async()=>{try{let r=a.listUsers();return r.success?JSON.stringify(r.data,null,2):`ERROR: ${r.error.message}`}catch(r){u("Error in listUsers tool:",r);let e=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:e},null,2)}`}}}),s.oauth?.enabled&&B(o,s);let n=o.getApp();return n.get("/",r=>{let e=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:`${e}${s.endpoint||"/mcp"}`,health:`${e}/health`,ui:`${e}/ui/:userId`,...s.oauth?.enabled&&{oauth:{authorization:`${e}/oauth/authorize`,token:`${e}/oauth/token`,jwks:`${e}/oauth/jwks`,register:`${e}/oauth/register`}}},timestamp:new Date().toISOString()};return r.json(t)}),L(n,a,s),u("\u2713 FastMCP server created"),{server:o,duckpond:a}}function B(s,a){let h=s.getApp();setInterval(()=>{let o=Date.now();for(let[n,r]of v.entries())o-r.createdAt>6e5&&v.delete(n);for(let[n,r]of _.entries())o-r.createdAt>2592e6&&_.delete(n)},6e4),h.get("/oauth/authorize",o=>{let n=o.req.query(),r=n.response_type,e=n.redirect_uri,t=n.state,c=n.code_challenge,i=n.code_challenge_method,l=n.client_id;if(r!=="code")return o.json({error:"unsupported_response_type",error_description:"Only 'code' response type is supported"},400);if(!e)return o.json({error:"invalid_request",error_description:"redirect_uri is required"},400);if(c&&(!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 d=`
2
+ <!DOCTYPE html>
3
+ <html>
4
+ <head>
5
+ <title>OAuth Login - DuckPond MCP Server</title>
6
+ <style>
7
+ body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }
8
+ .form-group { margin-bottom: 15px; }
9
+ label { display: block; margin-bottom: 5px; font-weight: bold; }
10
+ input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
11
+ button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
12
+ button:hover { background: #005a87; }
13
+ .app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }
14
+ </style>
15
+ </head>
16
+ <body>
17
+ <div class="app-info">
18
+ <h3>\u{1F510} OAuth Authorization</h3>
19
+ <p><strong>Application:</strong> ${l||"MCP Client"}</p>
20
+ <p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>
21
+ </div>
22
+
23
+ <form method="POST" action="/oauth/authorize">
24
+ <input type="hidden" name="response_type" value="${r}">
25
+ <input type="hidden" name="redirect_uri" value="${e}">
26
+ <input type="hidden" name="state" value="${t||""}">
27
+ <input type="hidden" name="code_challenge" value="${c||""}">
28
+ <input type="hidden" name="code_challenge_method" value="${i||""}">
29
+ <input type="hidden" name="client_id" value="${l||""}">
30
+
31
+ <div class="form-group">
32
+ <label for="username">Username:</label>
33
+ <input type="text" id="username" name="username" required>
34
+ </div>
35
+
36
+ <div class="form-group">
37
+ <label for="password">Password:</label>
38
+ <input type="password" id="password" name="password" required>
39
+ </div>
40
+
41
+ <button type="submit">Authorize Application</button>
42
+ </form>
43
+ </body>
44
+ </html>`;return o.html(d)}),h.post("/oauth/authorize",async o=>{try{let n=await o.req.text(),r=new URLSearchParams(n),e=r.get("username"),t=r.get("password"),c=r.get("redirect_uri"),i=r.get("state"),l=r.get("code_challenge"),d=r.get("code_challenge_method");if(e!==a.oauth?.username||t!==a.oauth?.password)return o.html(`
45
+ <!DOCTYPE html>
46
+ <html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>
47
+ <body><div class="error">\u274C Invalid username or password</div><a href="javascript:history.back()">\u2190 Try Again</a></body></html>`,401);let f=w(16).toString("hex");v.set(f,{createdAt:Date.now(),redirectUri:c||"",codeChallenge:l||void 0,codeChallengeMethod:d||void 0,userId:a.oauth?.userId||e||"oauth-user"});let p=new M(c||"");return p.searchParams.set("code",f),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(),r=new URLSearchParams(n),e=r.get("grant_type"),t=r.get("code"),c=r.get("redirect_uri"),i=r.get("code_verifier"),l=r.get("refresh_token");if(e==="refresh_token"){if(!l)return o.json({error:"invalid_request",error_description:"refresh_token is required for refresh_token grant type"},400);let g=_.get(l);if(!g)return o.json({error:"invalid_grant",error_description:"Invalid or expired refresh token"},400);_.delete(l);let j={sub:g.userId,email:g.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`},k=w(32).toString("hex");_.set(k,{createdAt:Date.now(),userId:g.userId,email:g.email});let q=S.sign(j,x);return o.json({access_token:q,token_type:"Bearer",expires_in:b,scope:"read write",refresh_token:k})}if(e!=="authorization_code")return o.json({error:"unsupported_grant_type",error_description:"Only 'authorization_code' and 'refresh_token' grant types are supported"},400);let d=v.get(t||"");if(!d)return o.json({error:"invalid_grant",error_description:"Invalid or expired authorization code"},400);if(d.redirectUri&&d.redirectUri!==c)return o.json({error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(d.codeChallenge){if(!i)return o.json({error:"invalid_grant",error_description:"code_verifier is required when code_challenge was used"},400);let g;if(d.codeChallengeMethod==="S256"?g=N("sha256").update(i).digest().toString("base64url"):g=i,g!==d.codeChallenge)return o.json({error:"invalid_grant",error_description:"Invalid code_verifier"},400)}v.delete(t);let f={sub:d.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:d.userId,email:a.oauth?.email});let m=S.sign(f,x);return o.json({access_token:m,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){u("Error parsing request body:",c)}let r=`client-${w(8).toString("hex")}`,e=w(16).toString("hex"),t={client_id:r,client_secret:e,client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:n.grant_types||["authorization_code"],response_types:n.response_types||["code"],redirect_uris:n.redirect_uris||[],token_endpoint_auth_method:n.token_endpoint_auth_method||"client_secret_post"};return n.client_name&&(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)}}),u("\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",r=>{if(!a.getCurrentUIUser()){let t=a.listUsers();return r.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 r.redirect("/ui/")}),s.get("/ui/:userId",async r=>{let e=r.req.param("userId");u(`Starting UI for user: ${e}`);let t=await a.startUI(e);return t.success?r.redirect("/ui/"):r.json({error:"Failed to start UI",message:t.error.message,details:t.error.details},500)}),s.all("/ui/*",async r=>{if(!a.getCurrentUIUser())return r.json({error:"No UI active",message:"Start UI by visiting /ui/:userId first"},400);let t=r.req.path.replace(/^\/ui/,"")||"/";try{let c=`http://localhost:${n}${t}`,i=new M(r.req.url);i.search;let l=new Headers;r.req.raw.headers.forEach((p,m)=>{m.toLowerCase()!=="host"&&l.set(m,p)});let d=await fetch(c+i.search,{method:r.req.method,headers:l,body:["GET","HEAD"].includes(r.req.method)?void 0:await r.req.arrayBuffer()}),f=new Headers;return d.headers.forEach((p,m)=>{["transfer-encoding","connection"].includes(m.toLowerCase())||f.set(m,p)}),new Response(d.body,{status:d.status,statusText:d.statusText,headers:f})}catch(c){return u(`UI proxy error: ${c instanceof Error?c.message:String(c)}`),r.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)}}),u("\u2713 UI endpoints added")}async function te(s,a){let{server:h,duckpond:o}=F(s),n=await o.init();if(!n.success)throw new Error(`Failed to initialize DuckPond: ${n.error.message}`);u("DuckPond initialized successfully"),s.ui?.internalPort&&o.setUIPort(s.ui.internalPort),a==="stdio"?(await h.start({transportType:"stdio"}),u("\u2713 FastMCP server running with stdio transport"),s.ui?.enabled&&await E({port:s.ui.port,duckpond:o})):(await h.start({transportType:"httpStream",httpStream:{port:s.port||3e3,endpoint:s.endpoint||"/mcp"}}),u(`\u2713 FastMCP server running on http://0.0.0.0:${s.port||3e3}${s.endpoint||"/mcp"}`),u("\u{1F50C} Connect with StreamableHTTPClientTransport")),process.on("SIGINT",async()=>{u("Received SIGINT, closing server..."),await o.close(),process.exit(0)}),process.on("SIGTERM",async()=>{u("Received SIGTERM, closing server..."),await o.close(),process.exit(0)})}export{F as a,te as b};
48
+ //# sourceMappingURL=chunk-VGBI52XK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { FastMCP } from \"@jordanburke/fastmcp\"\nimport { createHash, randomBytes } from \"crypto\"\nimport { createRequire } from \"module\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport * as jwt from \"jsonwebtoken\"\nimport { URL } from \"url\"\nimport { z } from \"zod\"\n\nimport { DuckPondServer, type DuckPondServerConfig } from \"./server-core\"\nimport {\n detachUserSchema,\n executeSchema,\n getDefaultUserId,\n getUserStatsSchema,\n isAttachedSchema,\n listUsersSchema,\n querySchema,\n resolveUserId,\n} from \"./tools\"\nimport { 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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,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"]}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as i}from"./chunk-TAP5LWZ7.js";import"./chunk-SU42EK5H.js";import"./chunk-43NWQIU3.js";import{b as a}from"./chunk-A3S6D44B.js";import{webcrypto as p}from"crypto";import{Command as _}from"commander";import{createRequire as C}from"module";globalThis.crypto||(globalThis.crypto=p);var U=C(import.meta.url),O=U("../package.json"),t=a.main;function m(){let r={memoryLimit:process.env.DUCKPOND_MEMORY_LIMIT||"4GB",threads:parseInt(process.env.DUCKPOND_THREADS||"4"),maxActiveUsers:parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS||"10"),evictionTimeout:parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT||"300000"),cacheType:process.env.DUCKPOND_CACHE_TYPE||"disk",strategy:process.env.DUCKPOND_STRATEGY||"parquet",tempDir:process.env.DUCKPOND_TEMP_DIR,cacheDir:process.env.DUCKPOND_CACHE_DIR};return process.env.DUCKPOND_R2_ACCOUNT_ID&&(r.r2={accountId:process.env.DUCKPOND_R2_ACCOUNT_ID,accessKeyId:process.env.DUCKPOND_R2_ACCESS_KEY_ID||"",secretAccessKey:process.env.DUCKPOND_R2_SECRET_ACCESS_KEY||"",bucket:process.env.DUCKPOND_R2_BUCKET||""}),process.env.DUCKPOND_S3_REGION&&(r.s3={region:process.env.DUCKPOND_S3_REGION,accessKeyId:process.env.DUCKPOND_S3_ACCESS_KEY_ID||"",secretAccessKey:process.env.DUCKPOND_S3_SECRET_ACCESS_KEY||"",bucket:process.env.DUCKPOND_S3_BUCKET||""},process.env.DUCKPOND_S3_ENDPOINT&&(r.s3.endpoint=process.env.DUCKPOND_S3_ENDPOINT)),r}var D=new _;D.name("duckpond-mcp-server").description("MCP server for multi-tenant DuckDB management with R2/S3 storage").version(O.version).option("-t, --transport <type>","Transport mode: stdio or http","stdio").option("-p, --port <port>","HTTP port (when using http transport)","3000").action(async r=>{try{let e=m();t(`Starting DuckPond MCP Server with ${r.transport} transport`),t("Configuration:",{memoryLimit:e.memoryLimit,threads:e.threads,maxActiveUsers:e.maxActiveUsers,strategy:e.strategy,tempDir:e.tempDir,cacheDir:e.cacheDir,cacheType:e.cacheType,hasR2:!!e.r2,hasS3:!!e.s3});let o;if(process.env.DUCKPOND_OAUTH_ENABLED==="true"){let n=process.env.DUCKPOND_OAUTH_USERNAME,c=process.env.DUCKPOND_OAUTH_PASSWORD;(!n||!c)&&(console.error("\u274C OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required"),process.exit(1)),o={enabled:!0,username:n,password:c,userId:process.env.DUCKPOND_OAUTH_USER_ID||n,email:process.env.DUCKPOND_OAUTH_EMAIL,issuer:process.env.DUCKPOND_OAUTH_ISSUER||`http://localhost:${parseInt(r.port)||3e3}`,resource:process.env.DUCKPOND_OAUTH_RESOURCE},console.error("\u{1F510} OAuth enabled with username/password authentication"),console.error(` Username: ${o.username}`),console.error(` User ID: ${o.userId}`),console.error(" \u2713 Login form will be shown at authorization endpoint")}let s;process.env.DUCKPOND_BASIC_AUTH_USERNAME&&process.env.DUCKPOND_BASIC_AUTH_PASSWORD&&(s={username:process.env.DUCKPOND_BASIC_AUTH_USERNAME,password:process.env.DUCKPOND_BASIC_AUTH_PASSWORD,userId:process.env.DUCKPOND_BASIC_AUTH_USER_ID,email:process.env.DUCKPOND_BASIC_AUTH_EMAIL},console.error("\u{1F510} Basic authentication enabled"),console.error(` Username: ${s.username}`),console.error(` User ID: ${s.userId||s.username}`)),r.transport==="stdio"||r.transport==="http"?await i({config:e,port:parseInt(r.port)||3e3,endpoint:"/mcp",oauth:o,basicAuth:s},r.transport==="stdio"?"stdio":"http"):(t(`Unknown transport: ${r.transport}`),process.exit(1))}catch(e){t("Fatal error:",e),console.error("Fatal error:",e),process.exit(1)}});D.parse();
2
+ import{b as U}from"./chunk-VGBI52XK.js";import"./chunk-R65UMTEX.js";import"./chunk-SIVPP6RP.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { Command } from \"commander\"\nimport { createRequire } from \"module\"\n\nimport type { OAuthConfig } from \"./server\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport { startServer } from \"./server\"\nimport type { DuckPondServerConfig } from \"./server-core\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.main\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n const config: DuckPondServerConfig = {\n memoryLimit: process.env.DUCKPOND_MEMORY_LIMIT || \"4GB\",\n threads: parseInt(process.env.DUCKPOND_THREADS || \"4\"),\n maxActiveUsers: parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS || \"10\"),\n evictionTimeout: parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT || \"300000\"),\n cacheType: (process.env.DUCKPOND_CACHE_TYPE as \"disk\" | \"memory\" | \"noop\") || \"disk\",\n strategy: (process.env.DUCKPOND_STRATEGY as \"parquet\" | \"duckdb\" | \"hybrid\") || \"parquet\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR,\n }\n\n // R2 configuration\n if (process.env.DUCKPOND_R2_ACCOUNT_ID) {\n config.r2 = {\n accountId: process.env.DUCKPOND_R2_ACCOUNT_ID,\n accessKeyId: process.env.DUCKPOND_R2_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_R2_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_R2_BUCKET || \"\",\n }\n }\n\n // S3 configuration\n if (process.env.DUCKPOND_S3_REGION) {\n config.s3 = {\n region: process.env.DUCKPOND_S3_REGION,\n accessKeyId: process.env.DUCKPOND_S3_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_S3_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_S3_BUCKET || \"\",\n }\n\n if (process.env.DUCKPOND_S3_ENDPOINT) {\n config.s3.endpoint = process.env.DUCKPOND_S3_ENDPOINT\n }\n }\n\n return config\n}\n\n/**\n * Main CLI program\n */\nconst program = new Command()\n\nprogram\n .name(\"duckpond-mcp-server\")\n .description(\"MCP server for multi-tenant DuckDB management with R2/S3 storage\")\n .version(packageJson.version)\n .option(\"-t, --transport <type>\", \"Transport mode: stdio or http\", \"stdio\")\n .option(\"-p, --port <port>\", \"HTTP port (when using http transport)\", \"3000\")\n .action(async (options) => {\n try {\n const config = getConfigFromEnv()\n\n log(`Starting DuckPond MCP Server with ${options.transport} transport`)\n log(\"Configuration:\", {\n memoryLimit: config.memoryLimit,\n threads: config.threads,\n maxActiveUsers: config.maxActiveUsers,\n strategy: config.strategy,\n tempDir: config.tempDir,\n cacheDir: config.cacheDir,\n cacheType: config.cacheType,\n hasR2: !!config.r2,\n hasS3: !!config.s3,\n })\n\n // Load OAuth configuration from environment variables (for HTTP transport)\n let oauthConfig: OAuthConfig | undefined\n if (process.env.DUCKPOND_OAUTH_ENABLED === \"true\") {\n const username = process.env.DUCKPOND_OAUTH_USERNAME\n const password = process.env.DUCKPOND_OAUTH_PASSWORD\n\n if (!username || !password) {\n console.error(\"❌ OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required\")\n process.exit(1)\n }\n\n oauthConfig = {\n enabled: true,\n username,\n password,\n userId: process.env.DUCKPOND_OAUTH_USER_ID || username,\n email: process.env.DUCKPOND_OAUTH_EMAIL,\n issuer: process.env.DUCKPOND_OAUTH_ISSUER || `http://localhost:${parseInt(options.port) || 3000}`,\n resource: process.env.DUCKPOND_OAUTH_RESOURCE,\n }\n\n console.error(\"🔐 OAuth enabled with username/password authentication\")\n console.error(` Username: ${oauthConfig.username}`)\n console.error(` User ID: ${oauthConfig.userId}`)\n console.error(\" ✓ Login form will be shown at authorization endpoint\")\n }\n\n // Load Basic Auth configuration from environment variables (for HTTP transport)\n let basicAuthConfig: { username: string; password: string; userId?: string; email?: string } | undefined\n if (process.env.DUCKPOND_BASIC_AUTH_USERNAME && process.env.DUCKPOND_BASIC_AUTH_PASSWORD) {\n basicAuthConfig = {\n username: process.env.DUCKPOND_BASIC_AUTH_USERNAME,\n password: process.env.DUCKPOND_BASIC_AUTH_PASSWORD,\n userId: process.env.DUCKPOND_BASIC_AUTH_USER_ID,\n email: process.env.DUCKPOND_BASIC_AUTH_EMAIL,\n }\n\n console.error(\"🔐 Basic authentication enabled\")\n console.error(` Username: ${basicAuthConfig.username}`)\n console.error(` User ID: ${basicAuthConfig.userId || basicAuthConfig.username}`)\n }\n\n // Start unified FastMCP server with appropriate transport\n if (options.transport === \"stdio\" || options.transport === \"http\") {\n await startServer(\n {\n config,\n port: parseInt(options.port) || 3000,\n endpoint: \"/mcp\",\n oauth: oauthConfig,\n basicAuth: basicAuthConfig,\n },\n options.transport === \"stdio\" ? \"stdio\" : \"http\",\n )\n } else {\n log(`Unknown transport: ${options.transport}`)\n process.exit(1)\n }\n } catch (error) {\n log(\"Fatal error:\", error)\n console.error(\"Fatal error:\", error)\n process.exit(1)\n }\n })\n\nprogram.parse()\n"],"mappings":";wIAGA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,YACxB,OAAS,iBAAAC,MAAqB,SALzB,WAAW,SACd,WAAW,OAASC,GAQtB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EAAcF,EAAQ,iBAAiB,EAKvCG,EAAMC,EAAQ,KAKpB,SAASC,GAAyC,CAChD,IAAMC,EAA+B,CACnC,YAAa,QAAQ,IAAI,uBAAyB,MAClD,QAAS,S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CAAC,EAEHR,EAAQ,MAAM","names":["webcrypto","Command","createRequire","webcrypto","require","createRequire","packageJson","log","loggers","getConfigFromEnv","config","program","Command","options","oauthConfig","username","password","basicAuthConfig","startServer","error"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { Command } from \"commander\"\nimport { createRequire } from \"module\"\n\nimport type { OAuthConfig } from \"./server\"\nimport { getDefaultUserId } from \"./tools\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport { startServer } from \"./server\"\nimport type { DuckPondServerConfig } from \"./server-core\"\nimport { startUIServer } from \"./ui-server\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.main\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n const config: DuckPondServerConfig = {\n memoryLimit: process.env.DUCKPOND_MEMORY_LIMIT || \"4GB\",\n threads: parseInt(process.env.DUCKPOND_THREADS || \"4\"),\n maxActiveUsers: parseInt(process.env.DUCKPOND_MAX_ACTIVE_USERS || \"10\"),\n evictionTimeout: parseInt(process.env.DUCKPOND_EVICTION_TIMEOUT || \"300000\"),\n cacheType: (process.env.DUCKPOND_CACHE_TYPE as \"disk\" | \"memory\" | \"noop\") || \"disk\",\n strategy: (process.env.DUCKPOND_STRATEGY as \"parquet\" | \"duckdb\" | \"hybrid\") || \"parquet\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR,\n }\n\n // R2 configuration\n if (process.env.DUCKPOND_R2_ACCOUNT_ID) {\n config.r2 = {\n accountId: process.env.DUCKPOND_R2_ACCOUNT_ID,\n accessKeyId: process.env.DUCKPOND_R2_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_R2_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_R2_BUCKET || \"\",\n }\n }\n\n // S3 configuration\n if (process.env.DUCKPOND_S3_REGION) {\n config.s3 = {\n region: process.env.DUCKPOND_S3_REGION,\n accessKeyId: process.env.DUCKPOND_S3_ACCESS_KEY_ID || \"\",\n secretAccessKey: process.env.DUCKPOND_S3_SECRET_ACCESS_KEY || \"\",\n bucket: process.env.DUCKPOND_S3_BUCKET || \"\",\n }\n\n if (process.env.DUCKPOND_S3_ENDPOINT) {\n config.s3.endpoint = process.env.DUCKPOND_S3_ENDPOINT\n }\n }\n\n return config\n}\n\n/**\n * Main CLI program\n */\nconst program = new Command()\n\nprogram\n .name(\"duckpond-mcp-server\")\n .description(\"MCP server for multi-tenant DuckDB management with R2/S3 storage\")\n .version(packageJson.version)\n .option(\"-t, --transport <type>\", \"Transport mode: stdio or http\", \"stdio\")\n .option(\"-p, --port <port>\", \"HTTP port (when using http transport)\", \"3000\")\n .option(\"--ui\", \"Enable DuckDB UI server (for stdio mode)\")\n .option(\"--ui-port <port>\", \"UI server port (default: 4000)\", \"4000\")\n .option(\"--ui-internal-port <port>\", \"Internal DuckDB UI port (default: 4213)\", \"4213\")\n .action(async (options) => {\n try {\n const config = getConfigFromEnv()\n\n const defaultUser = getDefaultUserId()\n log(`Starting DuckPond MCP Server with ${options.transport} transport`)\n log(\"Configuration:\", {\n memoryLimit: config.memoryLimit,\n threads: config.threads,\n maxActiveUsers: config.maxActiveUsers,\n strategy: config.strategy,\n tempDir: config.tempDir,\n cacheDir: config.cacheDir,\n cacheType: config.cacheType,\n hasR2: !!config.r2,\n hasS3: !!config.s3,\n defaultUser: defaultUser || \"(not set)\",\n })\n\n if (defaultUser) {\n console.error(`👤 Default user: ${defaultUser}`)\n }\n\n // Load OAuth configuration from environment variables (for HTTP transport)\n let oauthConfig: OAuthConfig | undefined\n if (process.env.DUCKPOND_OAUTH_ENABLED === \"true\") {\n const username = process.env.DUCKPOND_OAUTH_USERNAME\n const password = process.env.DUCKPOND_OAUTH_PASSWORD\n\n if (!username || !password) {\n console.error(\"❌ OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required\")\n process.exit(1)\n }\n\n oauthConfig = {\n enabled: true,\n username,\n password,\n userId: process.env.DUCKPOND_OAUTH_USER_ID || username,\n email: process.env.DUCKPOND_OAUTH_EMAIL,\n issuer: process.env.DUCKPOND_OAUTH_ISSUER || `http://localhost:${parseInt(options.port) || 3000}`,\n resource: process.env.DUCKPOND_OAUTH_RESOURCE,\n }\n\n console.error(\"🔐 OAuth enabled with username/password authentication\")\n console.error(` Username: ${oauthConfig.username}`)\n console.error(` User ID: ${oauthConfig.userId}`)\n console.error(\" ✓ Login form will be shown at authorization endpoint\")\n }\n\n // Load Basic Auth configuration from environment variables (for HTTP transport)\n let basicAuthConfig: { username: string; password: string; userId?: string; email?: string } | undefined\n if (process.env.DUCKPOND_BASIC_AUTH_USERNAME && process.env.DUCKPOND_BASIC_AUTH_PASSWORD) {\n basicAuthConfig = {\n username: process.env.DUCKPOND_BASIC_AUTH_USERNAME,\n password: process.env.DUCKPOND_BASIC_AUTH_PASSWORD,\n userId: process.env.DUCKPOND_BASIC_AUTH_USER_ID,\n email: process.env.DUCKPOND_BASIC_AUTH_EMAIL,\n }\n\n console.error(\"🔐 Basic authentication enabled\")\n console.error(` Username: ${basicAuthConfig.username}`)\n console.error(` User ID: ${basicAuthConfig.userId || basicAuthConfig.username}`)\n }\n\n // Parse UI options\n const uiEnabled = options.ui || process.env.DUCKPOND_UI_ENABLED === \"true\"\n const uiPort = parseInt(options.uiPort) || 4000\n const uiInternalPort = parseInt(options.uiInternalPort) || 4213\n\n if (uiEnabled && options.transport === \"stdio\") {\n console.error(`🖥️ UI server will be available at http://localhost:${uiPort}/ui`)\n }\n\n // Start unified FastMCP server with appropriate transport\n if (options.transport === \"stdio\" || options.transport === \"http\") {\n await startServer(\n {\n config,\n port: parseInt(options.port) || 3000,\n endpoint: \"/mcp\",\n oauth: oauthConfig,\n basicAuth: basicAuthConfig,\n ui: uiEnabled\n ? {\n enabled: true,\n port: uiPort,\n internalPort: uiInternalPort,\n }\n : undefined,\n },\n options.transport === \"stdio\" ? \"stdio\" : \"http\",\n )\n } else {\n log(`Unknown transport: ${options.transport}`)\n process.exit(1)\n }\n } catch (error) {\n log(\"Fatal error:\", error)\n console.error(\"Fatal error:\", error)\n process.exit(1)\n }\n })\n\nprogram.parse()\n"],"mappings":";gLAGA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,YACxB,OAAS,iBAAAC,MAAqB,SALzB,WAAW,SACd,WAAW,OAASC,GAStB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EAAcF,EAAQ,iBAAiB,EAMvCG,EAAMC,EAAQ,KAKpB,SAASC,GAAyC,CAChD,IAAMC,EAA+B,CACnC,YAAa,QAAQ,IAAI,uBAAyB,MAClD,QAAS,SAAS,QAAQ,IAAI,kBAAoB,GAAG,EACrD,eAAgB,SAAS,QAAQ,IAAI,2BAA6B,IAAI,EACtE,gBAAiB,SAAS,QAAQ,IAAI,2BAA6B,QAAQ,EAC3E,UAAY,QAAQ,IAAI,qBAAsD,OAC9E,SAAW,QAAQ,IAAI,mBAAyD,UAChF,QAAS,QAAQ,IAAI,kBACrB,SAAU,QAAQ,IAAI,kBACxB,EAGA,OAAI,QAAQ,IAAI,yBACdA,EAAO,GAAK,CACV,UAAW,QAAQ,IAAI,uBACvB,YAAa,QAAQ,IAAI,2BAA6B,GACtD,gBAAiB,QAAQ,IAAI,+BAAiC,GAC9D,OAAQ,QAAQ,IAAI,oBAAsB,EAC5C,GAIE,QAAQ,IAAI,qBACdA,EAAO,GAAK,CACV,OAAQ,QAAQ,IAAI,mBACpB,YAAa,QAAQ,IAAI,2BAA6B,GACtD,gBAAiB,QAAQ,IAAI,+BAAiC,GAC9D,OAAQ,QAAQ,IAAI,oBAAsB,EAC5C,EAEI,QAAQ,IAAI,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,EAAE,EACpD,QAAQ,MAAM,eAAeA,EAAY,MAAM,EAAE,EACjD,QAAQ,MAAM,8DAAyD,CACzE,CAGA,IAAIG,EACA,QAAQ,IAAI,8BAAgC,QAAQ,IAAI,+BAC1DA,EAAkB,CAChB,SAAU,QAAQ,IAAI,6BACtB,SAAU,QAAQ,IAAI,6BACtB,OAAQ,QAAQ,IAAI,4BACpB,MAAO,QAAQ,IAAI,yBACrB,EAEA,QAAQ,MAAM,wCAAiC,EAC/C,QAAQ,MAAM,gBAAgBA,EAAgB,QAAQ,EAAE,EACxD,QAAQ,MAAM,eAAeA,EAAgB,QAAUA,EAAgB,QAAQ,EAAE,GAInF,IAAMC,EAAYP,EAAQ,IAAM,QAAQ,IAAI,sBAAwB,OAC9DQ,EAAS,SAASR,EAAQ,MAAM,GAAK,IACrCS,EAAiB,SAAST,EAAQ,cAAc,GAAK,KAEvDO,GAAaP,EAAQ,YAAc,SACrC,QAAQ,MAAM,oEAAwDQ,CAAM,KAAK,EAI/ER,EAAQ,YAAc,SAAWA,EAAQ,YAAc,OACzD,MAAMU,EACJ,CACE,OAAAb,EACA,KAAM,SAASG,EAAQ,IAAI,GAAK,IAChC,SAAU,OACV,MAAOG,EACP,UAAWG,EACX,GAAIC,EACA,CACE,QAAS,GACT,KAAMC,EACN,aAAcC,CAChB,EACA,MACN,EACAT,EAAQ,YAAc,QAAU,QAAU,MAC5C,GAEAN,EAAI,sBAAsBM,EAAQ,SAAS,EAAE,EAC7C,QAAQ,KAAK,CAAC,EAElB,OAASW,EAAO,CACdjB,EAAI,eAAgBiB,CAAK,EACzB,QAAQ,MAAM,eAAgBA,CAAK,EACnC,QAAQ,KAAK,CAAC,CAChB,CACF,CAAC,EAEHb,EAAQ,MAAM","names":["webcrypto","Command","createRequire","webcrypto","require","createRequire","packageJson","log","loggers","getConfigFromEnv","config","program","Command","options","defaultUser","getDefaultUserId","oauthConfig","username","password","basicAuthConfig","uiEnabled","uiPort","uiInternalPort","startServer","error"]}
@@ -33,6 +33,8 @@ declare class DuckPondServer {
33
33
  private config;
34
34
  private pond;
35
35
  private initialized;
36
+ private currentUIUserId;
37
+ private uiInternalPort;
36
38
  constructor(config: DuckPondServerConfig);
37
39
  /**
38
40
  * Initialize the DuckPond instance
@@ -71,6 +73,29 @@ declare class DuckPondServer {
71
73
  * Close the DuckPond instance
72
74
  */
73
75
  close(): Promise<MCPResult<void>>;
76
+ /**
77
+ * Start DuckDB UI for a specific user
78
+ * Only one user's UI can be active at a time
79
+ */
80
+ startUI(userId: string): Promise<MCPResult<{
81
+ port: number;
82
+ }>>;
83
+ /**
84
+ * Stop the currently running DuckDB UI
85
+ */
86
+ stopUI(): Promise<MCPResult<void>>;
87
+ /**
88
+ * Get the user ID for the currently running UI
89
+ */
90
+ getCurrentUIUser(): string | null;
91
+ /**
92
+ * Set the internal port for DuckDB UI
93
+ */
94
+ setUIPort(port: number): void;
95
+ /**
96
+ * Get the internal port for DuckDB UI
97
+ */
98
+ getUIPort(): number;
74
99
  /**
75
100
  * Convert Either<Error, T> to MCPResult<T>
76
101
  */
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-SU42EK5H.js";import"./chunk-A3S6D44B.js";export{a as DuckPondServer};
1
+ import{a}from"./chunk-R65UMTEX.js";import"./chunk-A3S6D44B.js";export{a as DuckPondServer};
2
2
  //# sourceMappingURL=server-core.js.map
package/dist/server.d.ts CHANGED
@@ -22,6 +22,11 @@ type FastMCPServerOptions = {
22
22
  userId?: string;
23
23
  email?: string;
24
24
  };
25
+ ui?: {
26
+ enabled: boolean;
27
+ port: number;
28
+ internalPort?: number;
29
+ };
25
30
  };
26
31
  declare function createFastMCPServer(options: FastMCPServerOptions): {
27
32
  server: FastMCP;
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-TAP5LWZ7.js";import"./chunk-SU42EK5H.js";import"./chunk-43NWQIU3.js";import"./chunk-A3S6D44B.js";export{a as createFastMCPServer,b as startServer};
1
+ import{a,b}from"./chunk-VGBI52XK.js";import"./chunk-R65UMTEX.js";import"./chunk-SIVPP6RP.js";import"./chunk-MPMUZFRC.js";import"./chunk-A3S6D44B.js";export{a as createFastMCPServer,b as startServer};
2
2
  //# sourceMappingURL=server.js.map
@@ -2,61 +2,70 @@ import { z } from 'zod';
2
2
  import { DuckPondServer } from '../server-core.js';
3
3
  import 'duckpond';
4
4
 
5
+ /**
6
+ * Get the default user ID from environment variable
7
+ */
8
+ declare function getDefaultUserId(): string | undefined;
9
+ /**
10
+ * Resolve user ID from input or default
11
+ * @throws Error if no user ID is available
12
+ */
13
+ declare function resolveUserId(inputUserId?: string): string;
5
14
  /**
6
15
  * Zod schema for query tool
7
16
  */
8
17
  declare const querySchema: z.ZodObject<{
9
- userId: z.ZodString;
18
+ userId: z.ZodOptional<z.ZodString>;
10
19
  sql: z.ZodString;
11
20
  }, "strip", z.ZodTypeAny, {
12
- userId: string;
13
21
  sql: string;
22
+ userId?: string | undefined;
14
23
  }, {
15
- userId: string;
16
24
  sql: string;
25
+ userId?: string | undefined;
17
26
  }>;
18
27
  /**
19
28
  * Zod schema for execute tool
20
29
  */
21
30
  declare const executeSchema: z.ZodObject<{
22
- userId: z.ZodString;
31
+ userId: z.ZodOptional<z.ZodString>;
23
32
  sql: z.ZodString;
24
33
  }, "strip", z.ZodTypeAny, {
25
- userId: string;
26
34
  sql: string;
35
+ userId?: string | undefined;
27
36
  }, {
28
- userId: string;
29
37
  sql: string;
38
+ userId?: string | undefined;
30
39
  }>;
31
40
  /**
32
41
  * Zod schema for getUserStats tool
33
42
  */
34
43
  declare const getUserStatsSchema: z.ZodObject<{
35
- userId: z.ZodString;
44
+ userId: z.ZodOptional<z.ZodString>;
36
45
  }, "strip", z.ZodTypeAny, {
37
- userId: string;
46
+ userId?: string | undefined;
38
47
  }, {
39
- userId: string;
48
+ userId?: string | undefined;
40
49
  }>;
41
50
  /**
42
51
  * Zod schema for isAttached tool
43
52
  */
44
53
  declare const isAttachedSchema: z.ZodObject<{
45
- userId: z.ZodString;
54
+ userId: z.ZodOptional<z.ZodString>;
46
55
  }, "strip", z.ZodTypeAny, {
47
- userId: string;
56
+ userId?: string | undefined;
48
57
  }, {
49
- userId: string;
58
+ userId?: string | undefined;
50
59
  }>;
51
60
  /**
52
61
  * Zod schema for detachUser tool
53
62
  */
54
63
  declare const detachUserSchema: z.ZodObject<{
55
- userId: z.ZodString;
64
+ userId: z.ZodOptional<z.ZodString>;
56
65
  }, "strip", z.ZodTypeAny, {
57
- userId: string;
66
+ userId?: string | undefined;
58
67
  }, {
59
- userId: string;
68
+ userId?: string | undefined;
60
69
  }>;
61
70
  /**
62
71
  * Zod schema for listUsers tool
@@ -122,4 +131,4 @@ declare const tools: {
122
131
  };
123
132
  };
124
133
 
125
- export { detachUserSchema, executeSchema, getUserStatsSchema, isAttachedSchema, listUsersSchema, querySchema, tools };
134
+ export { detachUserSchema, executeSchema, getDefaultUserId, getUserStatsSchema, isAttachedSchema, listUsersSchema, querySchema, resolveUserId, tools };
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g}from"../chunk-43NWQIU3.js";import"../chunk-A3S6D44B.js";export{e as detachUserSchema,b as executeSchema,c as getUserStatsSchema,d as isAttachedSchema,f as listUsersSchema,a as querySchema,g as tools};
1
+ import{a,b,c,d,e,f,g,h,i}from"../chunk-MPMUZFRC.js";import"../chunk-A3S6D44B.js";export{g as detachUserSchema,d as executeSchema,a as getDefaultUserId,e as getUserStatsSchema,f as isAttachedSchema,h as listUsersSchema,c as querySchema,b as resolveUserId,i as tools};
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ import { DuckPondServer } from './server-core.js';
2
+ import 'duckpond';
3
+
4
+ type UIServerOptions = {
5
+ port: number;
6
+ duckpond: DuckPondServer;
7
+ };
8
+ /**
9
+ * Start a lightweight HTTP server for UI access in stdio mode
10
+ * This allows accessing DuckDB UI even when MCP is running over stdio
11
+ */
12
+ declare function startUIServer(options: UIServerOptions): Promise<void>;
13
+
14
+ export { type UIServerOptions, startUIServer };
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-SIVPP6RP.js";import"./chunk-A3S6D44B.js";export{a as startUIServer};
2
+ //# sourceMappingURL=ui-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "duckpond-mcp-server",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "MCP server for multi-tenant DuckDB management with R2/S3 storage",
5
5
  "keywords": [
6
6
  "mcp",
@@ -26,6 +26,7 @@
26
26
  "duckpond-mcp-server": "./dist/index.js"
27
27
  },
28
28
  "dependencies": {
29
+ "@hono/node-server": "^1.19.7",
29
30
  "@jordanburke/fastmcp": "3.26.700",
30
31
  "@types/express": "^5.0.6",
31
32
  "@types/jsonwebtoken": "^9.0.10",
@@ -33,6 +34,7 @@
33
34
  "debug": "^4.4.3",
34
35
  "duckpond": "^0.2.1",
35
36
  "express": "^5.2.1",
37
+ "hono": "^4.11.3",
36
38
  "jsonwebtoken": "^9.0.3",
37
39
  "zod": "^3.25.76"
38
40
  },
@@ -1,2 +0,0 @@
1
- import{b as o}from"./chunk-A3S6D44B.js";import{z as r}from"zod";var c=o.tools,u=r.object({userId:r.string().min(1).describe("User identifier"),sql:r.string().min(1).describe("SQL query to execute")}),a=r.object({userId:r.string().min(1).describe("User identifier"),sql:r.string().min(1).describe("SQL statement to execute (DDL/DML)")}),d=r.object({userId:r.string().min(1).describe("User identifier")}),l=r.object({userId:r.string().min(1).describe("User identifier")}),f=r.object({userId:r.string().min(1).describe("User identifier")}),m=r.object({}),S={async query(s,t){c(`Tool: query for user ${t.userId}`);let e=await s.query(t.userId,t.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2)}]}},async execute(s,t){c(`Tool: execute for user ${t.userId}`);let e=await s.execute(t.userId,t.sql);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2)}]}},async getUserStats(s,t){c(`Tool: getUserStats for user ${t.userId}`);let e=await s.getUserStats(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2)}]}},isAttached(s,t){c(`Tool: isAttached for user ${t.userId}`);let e=s.isAttached(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({attached:e.data,userId:t.userId},null,2)}]}},async detachUser(s,t){c(`Tool: detachUser for user ${t.userId}`);let e=await s.detachUser(t.userId);if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify({success:!0,message:`User ${t.userId} detached successfully`},null,2)}]}},listUsers(s,t){c("Tool: listUsers");let e=s.listUsers();if(!e.success)throw new Error(e.error.message);return{content:[{type:"text",text:JSON.stringify(e.data,null,2)}]}}};export{u as a,a as b,d as c,l as d,f as e,m as f,S as g};
2
- //# sourceMappingURL=chunk-43NWQIU3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\nimport type { DuckPondServer } from \"../server-core\"\nimport { loggers } from \"../utils/logger\"\n\nconst log = loggers.tools\n\n/**\n * Zod schema for query tool\n */\nexport const querySchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n sql: z.string().min(1).describe(\"SQL query to execute\"),\n})\n\n/**\n * Zod schema for execute tool\n */\nexport const executeSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n sql: z.string().min(1).describe(\"SQL statement to execute (DDL/DML)\"),\n})\n\n/**\n * Zod schema for getUserStats tool\n */\nexport const getUserStatsSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for isAttached tool\n */\nexport const isAttachedSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for detachUser tool\n */\nexport const detachUserSchema = z.object({\n userId: z.string().min(1).describe(\"User identifier\"),\n})\n\n/**\n * Zod schema for listUsers tool\n */\nexport const listUsersSchema = z.object({})\n\n/**\n * Tool implementations for MCP server\n */\nexport const tools = {\n /**\n * Execute a SQL query for a user\n */\n async query(server: DuckPondServer, input: z.infer<typeof querySchema>) {\n log(`Tool: query for user ${input.userId}`)\n const result = await server.query(input.userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Execute DDL/DML statement\n */\n async execute(server: DuckPondServer, input: z.infer<typeof executeSchema>) {\n log(`Tool: execute for user ${input.userId}`)\n const result = await server.execute(input.userId, input.sql)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Get user database statistics\n */\n async getUserStats(server: DuckPondServer, input: z.infer<typeof getUserStatsSchema>) {\n log(`Tool: getUserStats for user ${input.userId}`)\n const result = await server.getUserStats(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Check if user is attached\n */\n isAttached(server: DuckPondServer, input: z.infer<typeof isAttachedSchema>) {\n log(`Tool: isAttached for user ${input.userId}`)\n const result = server.isAttached(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n attached: result.data,\n userId: input.userId,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * Detach a user from cache\n */\n async detachUser(server: DuckPondServer, input: z.infer<typeof detachUserSchema>) {\n log(`Tool: detachUser for user ${input.userId}`)\n const result = await server.detachUser(input.userId)\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(\n {\n success: true,\n message: `User ${input.userId} detached successfully`,\n },\n null,\n 2,\n ),\n },\n ],\n }\n },\n\n /**\n * List all currently cached users\n */\n listUsers(server: DuckPondServer, _input: z.infer<typeof listUsersSchema>) {\n log(\"Tool: listUsers\")\n const result = server.listUsers()\n\n if (!result.success) {\n throw new Error(result.error.message)\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n }\n },\n}\n"],"mappings":"wCAAA,OAAS,KAAAA,MAAS,MAKlB,IAAMC,EAAMC,EAAQ,MAKPC,EAAcC,EAAE,OAAO,CAClC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,EACpD,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,sBAAsB,CACxD,CAAC,EAKYC,EAAgBD,EAAE,OAAO,CACpC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,EACpD,IAAKA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,oCAAoC,CACtE,CAAC,EAKYE,EAAqBF,EAAE,OAAO,CACzC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,CACtD,CAAC,EAKYG,EAAmBH,EAAE,OAAO,CACvC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,iBAAiB,CACtD,CAAC,EAKYI,EAAmBJ,EAAE,OAAO,CACvC,OAAQA,EAAE,OAAO,EAAE,IAAI,CAAC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,EAC/C,IAAMC,EAASF,EAAO,WAAWC,EAAM,MAAM,EAE7C,GAAI,CAACC,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,SAAUA,EAAO,KACjB,OAAQD,EAAM,MAChB,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,MAAM,WAAWD,EAAwBC,EAAyC,CAChFX,EAAI,6BAA6BW,EAAM,MAAM,EAAE,EAC/C,IAAMC,EAAS,MAAMF,EAAO,WAAWC,EAAM,MAAM,EAEnD,GAAI,CAACC,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UACT,CACE,QAAS,GACT,QAAS,QAAQD,EAAM,MAAM,wBAC/B,EACA,KACA,CACF,CACF,CACF,CACF,CACF,EAKA,UAAUD,EAAwBG,EAAyC,CACzEb,EAAI,iBAAiB,EACrB,IAAMY,EAASF,EAAO,UAAU,EAEhC,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,MAAM,OAAO,EAGtC,MAAO,CACL,QAAS,CACP,CACE,KAAM,OACN,KAAM,KAAK,UAAUA,EAAO,KAAM,KAAM,CAAC,CAC3C,CACF,CACF,CACF,CACF","names":["z","log","loggers","querySchema","z","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","tools","server","input","result","_input"]}
@@ -1,2 +0,0 @@
1
- import{a as n,b as o}from"./chunk-A3S6D44B.js";import{DuckPond as u}from"duckpond";var r=o.core,a=class{constructor(t){this.config=t;n(this,"pond",null);n(this,"initialized",!1);r("DuckPondServer created")}async init(){if(this.initialized)return r("Already initialized"),{success:!0,data:void 0};r("Initializing DuckPond...");let t=Date.now();this.pond=new u(this.config);let e=await this.pond.init();return this.handleEither(e,Date.now()-t)}async query(t,e){if(!this.pond)return this.notInitializedError();r(`Query for user ${t}: ${e.substring(0,100)}...`);let s=Date.now(),i=await this.pond.query(t,e);return this.handleEither(i,Date.now()-s)}async execute(t,e){if(!this.pond)return this.notInitializedError();r(`Execute for user ${t}: ${e.substring(0,100)}...`);let s=Date.now(),i=await this.pond.execute(t,e);return this.handleEither(i,Date.now()-s)}async getUserStats(t){if(!this.pond)return this.notInitializedError();r(`Getting stats for user ${t}`);let e=Date.now(),s=await this.pond.getUserStats(t);return this.handleEither(s,Date.now()-e)}isAttached(t){if(!this.pond)return this.notInitializedError();let e=this.pond.isAttached(t);return r(`User ${t} attached: ${e}`),{success:!0,data:e}}async detachUser(t){if(!this.pond)return this.notInitializedError();r(`Detaching user ${t}`);let e=Date.now(),s=await this.pond.detachUser(t);return this.handleEither(s,Date.now()-e)}listUsers(){if(!this.pond)return this.notInitializedError();r("Listing cached users");let t=this.pond.listUsers();return{success:!0,data:{users:t.users.toArray(),count:t.count,maxActiveUsers:t.maxActiveUsers,utilizationPercent:t.utilizationPercent}}}async close(){if(!this.pond)return{success:!0,data:void 0};r("Closing DuckPond...");let t=Date.now(),e=await this.pond.close();return this.initialized=!1,this.pond=null,this.handleEither(e,Date.now()-t)}handleEither(t,e){return t.fold(s=>({success:!1,error:{code:this.mapErrorCode(s.code),message:s.message,details:{originalCode:s.code,context:s.context,cause:s.cause?.message}}}),s=>({success:!0,data:s,executionTime:e}))}mapErrorCode(t){return{CONNECTION_FAILED:"SERVICE_UNAVAILABLE",CONNECTION_TIMEOUT:"TIMEOUT",R2_CONNECTION_ERROR:"SERVICE_UNAVAILABLE",S3_CONNECTION_ERROR:"SERVICE_UNAVAILABLE",USER_NOT_FOUND:"NOT_FOUND",USER_ALREADY_EXISTS:"ALREADY_EXISTS",USER_NOT_ATTACHED:"NOT_FOUND",QUERY_EXECUTION_ERROR:"INVALID_REQUEST",QUERY_TIMEOUT:"TIMEOUT",INVALID_SQL:"INVALID_REQUEST",MEMORY_LIMIT_EXCEEDED:"RESOURCE_EXHAUSTED",STORAGE_ERROR:"SERVICE_UNAVAILABLE",STORAGE_QUOTA_EXCEEDED:"RESOURCE_EXHAUSTED",INVALID_CONFIG:"INVALID_ARGUMENT",NOT_INITIALIZED:"FAILED_PRECONDITION",UNKNOWN_ERROR:"INTERNAL_ERROR"}[t]||"INTERNAL_ERROR"}notInitializedError(){return{success:!1,error:{code:"FAILED_PRECONDITION",message:"DuckPond not initialized. Call init() first."}}}};export{a};
2
- //# sourceMappingURL=chunk-SU42EK5H.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server-core.ts"],"sourcesContent":["import type { Either } from \"duckpond\"\nimport { DuckPond, type DuckPondConfig, type ErrorCode, type ListUsersResult, type UserStats } from \"duckpond\"\n\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.core\n\n/**\n * Result type for MCP tool responses\n */\nexport type MCPResult<T> =\n | {\n success: true\n data: T\n executionTime?: number\n }\n | {\n success: false\n error: {\n code: string\n message: string\n details?: {\n originalCode?: ErrorCode\n context?: Record<string, unknown>\n cause?: string\n }\n }\n }\n\n/**\n * Configuration for DuckPond MCP Server\n * Currently identical to DuckPondConfig, but can be extended with server-specific options\n */\nexport type DuckPondServerConfig = DuckPondConfig\n\n/**\n * Core DuckPond MCP Server\n *\n * Wraps DuckPond library with MCP-compatible result types\n */\nexport class DuckPondServer {\n private pond: DuckPond | null = null\n private initialized = false\n\n constructor(private config: DuckPondServerConfig) {\n log(\"DuckPondServer created\")\n }\n\n /**\n * Initialize the DuckPond instance\n */\n async init(): Promise<MCPResult<void>> {\n if (this.initialized) {\n log(\"Already initialized\")\n return { success: true, data: undefined }\n }\n\n log(\"Initializing DuckPond...\")\n const startTime = Date.now()\n\n this.pond = new DuckPond(this.config)\n const result = await this.pond.init()\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Execute a SQL query for a user\n */\n async query<T = unknown>(userId: string, sql: string): Promise<MCPResult<T[]>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Query for user ${userId}: ${sql.substring(0, 100)}...`)\n const startTime = Date.now()\n\n const result = await this.pond.query<T>(userId, sql)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Execute DDL/DML without returning results\n */\n async execute(userId: string, sql: string): Promise<MCPResult<void>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Execute for user ${userId}: ${sql.substring(0, 100)}...`)\n const startTime = Date.now()\n\n const result = await this.pond.execute(userId, sql)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Get statistics about a user's database\n */\n async getUserStats(userId: string): Promise<MCPResult<UserStats>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Getting stats for user ${userId}`)\n const startTime = Date.now()\n\n const result = await this.pond.getUserStats(userId)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Check if a user is currently cached\n */\n isAttached(userId: string): MCPResult<boolean> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n const attached = this.pond.isAttached(userId)\n log(`User ${userId} attached: ${attached}`)\n\n return {\n success: true,\n data: attached,\n }\n }\n\n /**\n * Manually detach a user from the cache\n */\n async detachUser(userId: string): Promise<MCPResult<void>> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(`Detaching user ${userId}`)\n const startTime = Date.now()\n\n const result = await this.pond.detachUser(userId)\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * List all currently cached users\n */\n listUsers(): MCPResult<{ users: string[]; count: number; maxActiveUsers: number; utilizationPercent: number }> {\n if (!this.pond) {\n return this.notInitializedError()\n }\n\n log(\"Listing cached users\")\n const result = this.pond.listUsers()\n\n return {\n success: true,\n data: {\n users: result.users.toArray(), // Convert List<string> to string[]\n count: result.count,\n maxActiveUsers: result.maxActiveUsers,\n utilizationPercent: result.utilizationPercent,\n },\n }\n }\n\n /**\n * Close the DuckPond instance\n */\n async close(): Promise<MCPResult<void>> {\n if (!this.pond) {\n return { success: true, data: undefined }\n }\n\n log(\"Closing DuckPond...\")\n const startTime = Date.now()\n\n const result = await this.pond.close()\n this.initialized = false\n this.pond = null\n\n return this.handleEither(result, Date.now() - startTime)\n }\n\n /**\n * Convert Either<Error, T> to MCPResult<T>\n */\n private handleEither<T>(\n result: Either<{ code: ErrorCode; message: string; cause?: Error; context?: Record<string, unknown> }, T>,\n executionTime: number,\n ): MCPResult<T> {\n return result.fold(\n (error) => ({\n success: false,\n error: {\n code: this.mapErrorCode(error.code),\n message: error.message,\n details: {\n originalCode: error.code,\n context: error.context,\n cause: error.cause?.message,\n },\n },\n }),\n (data) => ({\n success: true,\n data,\n executionTime,\n }),\n )\n }\n\n /**\n * Map DuckPond ErrorCode to MCP error code\n */\n private mapErrorCode(code: ErrorCode): string {\n const mapping: Record<ErrorCode, string> = {\n CONNECTION_FAILED: \"SERVICE_UNAVAILABLE\",\n CONNECTION_TIMEOUT: \"TIMEOUT\",\n R2_CONNECTION_ERROR: \"SERVICE_UNAVAILABLE\",\n S3_CONNECTION_ERROR: \"SERVICE_UNAVAILABLE\",\n USER_NOT_FOUND: \"NOT_FOUND\",\n USER_ALREADY_EXISTS: \"ALREADY_EXISTS\",\n USER_NOT_ATTACHED: \"NOT_FOUND\",\n QUERY_EXECUTION_ERROR: \"INVALID_REQUEST\",\n QUERY_TIMEOUT: \"TIMEOUT\",\n INVALID_SQL: \"INVALID_REQUEST\",\n MEMORY_LIMIT_EXCEEDED: \"RESOURCE_EXHAUSTED\",\n STORAGE_ERROR: \"SERVICE_UNAVAILABLE\",\n STORAGE_QUOTA_EXCEEDED: \"RESOURCE_EXHAUSTED\",\n INVALID_CONFIG: \"INVALID_ARGUMENT\",\n NOT_INITIALIZED: \"FAILED_PRECONDITION\",\n UNKNOWN_ERROR: \"INTERNAL_ERROR\",\n }\n\n return mapping[code] || \"INTERNAL_ERROR\"\n }\n\n /**\n * Helper for not initialized error\n */\n private notInitializedError<T>(): MCPResult<T> {\n return {\n success: false,\n error: {\n code: \"FAILED_PRECONDITION\",\n message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ACd,OAAOJ,EAAO,KACXK,IAAW,CACV,QAAS,GACT,MAAO,CACL,KAAM,KAAK,aAAaA,EAAM,IAAI,EAClC,QAASA,EAAM,QACf,QAAS,CACP,aAAcA,EAAM,KACpB,QAASA,EAAM,QACf,MAAOA,EAAM,OAAO,OACtB,CACF,CACF,GACCC,IAAU,CACT,QAAS,GACT,KAAAA,EACA,cAAAF,CACF,EACF,CACF,CAKQ,aAAaG,EAAyB,CAoB5C,MAnB2C,CACzC,kBAAmB,sBACnB,mBAAoB,UACpB,oBAAqB,sBACrB,oBAAqB,sBACrB,eAAgB,YAChB,oBAAqB,iBACrB,kBAAmB,YACnB,sBAAuB,kBACvB,cAAe,UACf,YAAa,kBACb,sBAAuB,qBACvB,cAAe,sBACf,uBAAwB,qBACxB,eAAgB,mBAChB,gBAAiB,sBACjB,cAAe,gBACjB,EAEeA,CAAI,GAAK,gBAC1B,CAKQ,qBAAuC,CAC7C,MAAO,CACL,QAAS,GACT,MAAO,CACL,KAAM,sBACN,QAAS,8CACX,CACF,CACF,CACF","names":["DuckPond","log","loggers","DuckPondServer","config","__publicField","startTime","DuckPond","result","userId","sql","attached","executionTime","error","data","code"]}
@@ -1,48 +0,0 @@
1
- import{a as C}from"./chunk-SU42EK5H.js";import{a as O,b as T,c as $,d as A,e as I,f as P}from"./chunk-43NWQIU3.js";import{b as R}from"./chunk-A3S6D44B.js";import{webcrypto as z}from"crypto";import{FastMCP as E}from"@jordanburke/fastmcp";import{createHash as D,randomBytes as f}from"crypto";import{createRequire as j}from"module";import*as y from"jsonwebtoken";import{URL as N}from"url";globalThis.crypto||(globalThis.crypto=z);var q=j(import.meta.url),v=q("../package.json"),u=R.fastmcp,b=process.env.DUCKPOND_JWT_SECRET||f(32).toString("hex"),S=process.env.DUCKPOND_JWT_EXPIRES_IN?parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN,10):365*24*60*60,_=new Map,m=new Map;function J(t){u("\u{1F680} Initializing FastMCP server...");let i=new C(t.config),h={name:"duckpond",version:v.version,health:{enabled:!0,path:"/health",status:200,message:JSON.stringify({status:"healthy",service:"duckpond-mcp-server",version:v.version,timestamp:new Date().toISOString()})}},s=t.oauth?.enabled||t.basicAuth?new E({...h,oauth:{enabled:!0,authorizationServer:{issuer:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,authorizationEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/authorize`,tokenEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/token`,jwksUri:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/jwks`,registrationEndpoint:`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/oauth/register`,responseTypesSupported:["code"],grantTypesSupported:["authorization_code"],tokenEndpointAuthMethodsSupported:["client_secret_post","client_secret_basic"],codeChallengeMethodsSupported:["S256","plain"]},protectedResource:{resource:process.env.DUCKPOND_OAUTH_RESOURCE||t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`,authorizationServers:[t.oauth?.issuer||`http://localhost:${t.port||3e3}`]}},authenticate:r=>{let e=r.headers?.authorization,n=t.oauth?.issuer||`http://localhost:${t.port||3e3}`;if(!e)throw t.oauth?.enabled?new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required. Please authenticate via OAuth."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${n}/oauth/authorize", resource="${n}/.well-known/oauth-protected-resource"`}}):new Response(JSON.stringify({error:"unauthorized",error_description:"Authorization required."}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json"}});if(t.basicAuth&&e.startsWith("Basic ")){let c=Buffer.from(e.slice(6),"base64").toString("utf-8"),[a,d]=c.split(":");if(a===t.basicAuth.username&&d===t.basicAuth.password)return Promise.resolve({userId:t.basicAuth.userId||a,email:t.basicAuth.email||`${a}@example.com`,scope:"read write"});throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid username or password"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Basic realm="MCP"'}})}if(t.oauth?.enabled&&e.startsWith("Bearer ")){let c=e.slice(7);try{let a=y.verify(c,b);if(!a.sub||!a.iat||!a.exp)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid token structure"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid token structure"'}});let d=t.oauth?.resource||`${n}/mcp`;if(a.aud&&a.aud!==d)throw new Response(JSON.stringify({error:"invalid_token",error_description:"Token audience mismatch"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Token audience mismatch"'}});return Promise.resolve({userId:a.sub,email:a.email||"",scope:a.scope||"read write"})}catch(a){throw a instanceof Response?a:new Response(JSON.stringify({error:"invalid_token",error_description:"Invalid or expired token"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":'Bearer realm="MCP", error="invalid_token", error_description="Invalid or expired token"'}})}}throw new Response(JSON.stringify({error:"unauthorized",error_description:"Invalid authorization header format"}),{status:401,statusText:"Unauthorized",headers:{"Content-Type":"application/json","WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${n}/oauth/authorize", resource="${n}/.well-known/oauth-protected-resource"`}})}}):new E(h);return s.addTool({name:"query",description:"Execute a SQL query for a specific user and return results",parameters:O,execute:async r=>{try{let e=await i.query(r.userId,r.sql);return e.success?JSON.stringify({rows:e.data,rowCount:e.data.length,executionTime:e.executionTime},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in query tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"execute",description:"Execute SQL statement (DDL/DML) for a specific user without returning results",parameters:T,execute:async r=>{try{let e=await i.execute(r.userId,r.sql);return e.success?JSON.stringify({success:!0,message:"Statement executed successfully",executionTime:e.executionTime},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in execute tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"getUserStats",description:"Get statistics about a user's database (memory usage, query count, etc.)",parameters:$,execute:async r=>{try{let e=await i.getUserStats(r.userId);return e.success?JSON.stringify({...e.data,lastAccess:e.data.lastAccess.toISOString()},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in getUserStats tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"isAttached",description:"Check if a user's database is currently cached in memory",parameters:A,execute:async r=>{try{let e=i.isAttached(r.userId);return e.success?JSON.stringify({attached:e.data,userId:r.userId},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in isAttached tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"detachUser",description:"Manually detach a user's database from the cache to free resources",parameters:I,execute:async r=>{try{let e=await i.detachUser(r.userId);return e.success?JSON.stringify({success:!0,message:`User ${r.userId} detached successfully`},null,2):`ERROR: ${e.error.message}`}catch(e){u("Error in detachUser tool:",e);let n=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:n},null,2)}`}}}),s.addTool({name:"listUsers",description:"List all currently cached users and cache statistics",parameters:P,execute:async()=>{try{let r=i.listUsers();return r.success?JSON.stringify(r.data,null,2):`ERROR: ${r.error.message}`}catch(r){u("Error in listUsers tool:",r);let e=r instanceof Error?r.message:String(r);return`ERROR: ${JSON.stringify({error:e},null,2)}`}}}),t.oauth?.enabled&&W(s,t),s.getApp().get("/",r=>{let e=t.oauth?.issuer||`http://localhost:${t.port||3e3}`,n={name:"DuckPond MCP Server",version:v.version,description:"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage",service:"duckpond-mcp-server",capabilities:{tools:["query","execute","getUserStats","isAttached","detachUser","listUsers"],transports:["stdio","http"],authentication:{oauth:t.oauth?.enabled||!1,basicAuth:!!t.basicAuth}},endpoints:{mcp:`${e}${t.endpoint||"/mcp"}`,health:`${e}/health`,...t.oauth?.enabled&&{oauth:{authorization:`${e}/oauth/authorize`,token:`${e}/oauth/token`,jwks:`${e}/oauth/jwks`,register:`${e}/oauth/register`}}},timestamp:new Date().toISOString()};return r.json(n)}),u("\u2713 FastMCP server created"),{server:s,duckpond:i}}function W(t,i){let h=t.getApp();setInterval(()=>{let s=Date.now();for(let[o,r]of _.entries())s-r.createdAt>6e5&&_.delete(o);for(let[o,r]of m.entries())s-r.createdAt>2592e6&&m.delete(o)},6e4),h.get("/oauth/authorize",s=>{let o=s.req.query(),r=o.response_type,e=o.redirect_uri,n=o.state,c=o.code_challenge,a=o.code_challenge_method,d=o.client_id;if(r!=="code")return s.json({error:"unsupported_response_type",error_description:"Only 'code' response type is supported"},400);if(!e)return s.json({error:"invalid_request",error_description:"redirect_uri is required"},400);if(c&&(!a||!["S256","plain"].includes(a)))return s.json({error:"invalid_request",error_description:"Invalid code_challenge_method. Only 'S256' and 'plain' are supported"},400);let l=`
2
- <!DOCTYPE html>
3
- <html>
4
- <head>
5
- <title>OAuth Login - DuckPond MCP Server</title>
6
- <style>
7
- body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }
8
- .form-group { margin-bottom: 15px; }
9
- label { display: block; margin-bottom: 5px; font-weight: bold; }
10
- input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
11
- button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
12
- button:hover { background: #005a87; }
13
- .app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }
14
- </style>
15
- </head>
16
- <body>
17
- <div class="app-info">
18
- <h3>\u{1F510} OAuth Authorization</h3>
19
- <p><strong>Application:</strong> ${d||"MCP Client"}</p>
20
- <p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>
21
- </div>
22
-
23
- <form method="POST" action="/oauth/authorize">
24
- <input type="hidden" name="response_type" value="${r}">
25
- <input type="hidden" name="redirect_uri" value="${e}">
26
- <input type="hidden" name="state" value="${n||""}">
27
- <input type="hidden" name="code_challenge" value="${c||""}">
28
- <input type="hidden" name="code_challenge_method" value="${a||""}">
29
- <input type="hidden" name="client_id" value="${d||""}">
30
-
31
- <div class="form-group">
32
- <label for="username">Username:</label>
33
- <input type="text" id="username" name="username" required>
34
- </div>
35
-
36
- <div class="form-group">
37
- <label for="password">Password:</label>
38
- <input type="password" id="password" name="password" required>
39
- </div>
40
-
41
- <button type="submit">Authorize Application</button>
42
- </form>
43
- </body>
44
- </html>`;return s.html(l)}),h.post("/oauth/authorize",async s=>{try{let o=await s.req.text(),r=new URLSearchParams(o),e=r.get("username"),n=r.get("password"),c=r.get("redirect_uri"),a=r.get("state"),d=r.get("code_challenge"),l=r.get("code_challenge_method");if(e!==i.oauth?.username||n!==i.oauth?.password)return s.html(`
45
- <!DOCTYPE html>
46
- <html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>
47
- <body><div class="error">\u274C Invalid username or password</div><a href="javascript:history.back()">\u2190 Try Again</a></body></html>`,401);let w=f(16).toString("hex");_.set(w,{createdAt:Date.now(),redirectUri:c||"",codeChallenge:d||void 0,codeChallengeMethod:l||void 0,userId:i.oauth?.userId||e||"oauth-user"});let g=new N(c||"");return g.searchParams.set("code",w),a&&g.searchParams.set("state",a),s.redirect(g.toString(),302)}catch{return s.json({error:"invalid_request",error_description:"Failed to process authorization request"},400)}}),h.post("/oauth/token",async s=>{let o=await s.req.text(),r=new URLSearchParams(o),e=r.get("grant_type"),n=r.get("code"),c=r.get("redirect_uri"),a=r.get("code_verifier"),d=r.get("refresh_token");if(e==="refresh_token"){if(!d)return s.json({error:"invalid_request",error_description:"refresh_token is required for refresh_token grant type"},400);let p=m.get(d);if(!p)return s.json({error:"invalid_grant",error_description:"Invalid or expired refresh token"},400);m.delete(d);let M={sub:p.userId,email:p.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+S,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},x=f(32).toString("hex");m.set(x,{createdAt:Date.now(),userId:p.userId,email:p.email});let U=y.sign(M,b);return s.json({access_token:U,token_type:"Bearer",expires_in:S,scope:"read write",refresh_token:x})}if(e!=="authorization_code")return s.json({error:"unsupported_grant_type",error_description:"Only 'authorization_code' and 'refresh_token' grant types are supported"},400);let l=_.get(n||"");if(!l)return s.json({error:"invalid_grant",error_description:"Invalid or expired authorization code"},400);if(l.redirectUri&&l.redirectUri!==c)return s.json({error:"invalid_grant",error_description:"redirect_uri mismatch"},400);if(l.codeChallenge){if(!a)return s.json({error:"invalid_grant",error_description:"code_verifier is required when code_challenge was used"},400);let p;if(l.codeChallengeMethod==="S256"?p=D("sha256").update(a).digest().toString("base64url"):p=a,p!==l.codeChallenge)return s.json({error:"invalid_grant",error_description:"Invalid code_verifier"},400)}_.delete(n);let w={sub:l.userId,email:i.oauth?.email||"",scope:"read write",iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+S,iss:i.oauth?.issuer||`http://localhost:${i.port||3e3}`,aud:i.oauth?.resource||`${i.oauth?.issuer||`http://localhost:${i.port||3e3}`}/mcp`},g=f(32).toString("hex");m.set(g,{createdAt:Date.now(),userId:l.userId,email:i.oauth?.email});let k=y.sign(w,b);return s.json({access_token:k,token_type:"Bearer",expires_in:S,scope:"read write",refresh_token:g})}),h.get("/oauth/jwks",s=>s.json({keys:[{kty:"oct",use:"sig",kid:"duckpond-hmac-key",alg:"HS256"}]})),h.post("/oauth/register",async s=>{try{let o={};try{let c=await s.req.text();if(c&&c!=="[object Object]")try{o=JSON.parse(c)}catch{o=Object.fromEntries(new URLSearchParams(c))}}catch(c){u("Error parsing request body:",c)}let r=`client-${f(8).toString("hex")}`,e=f(16).toString("hex"),n={client_id:r,client_secret:e,client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:o.grant_types||["authorization_code"],response_types:o.response_types||["code"],redirect_uris:o.redirect_uris||[],token_endpoint_auth_method:o.token_endpoint_auth_method||"client_secret_post"};return o.client_name&&(n.client_name=o.client_name),o.scope&&(n.scope=o.scope),s.json(n,201)}catch(o){return s.json({error:"invalid_client_metadata",error_description:"Invalid client registration request: "+(o instanceof Error?o.message:String(o))},400)}}),u("\u2713 OAuth flow endpoints added")}async function Y(t,i){let{server:h,duckpond:s}=J(t),o=await s.init();if(!o.success)throw new Error(`Failed to initialize DuckPond: ${o.error.message}`);u("DuckPond initialized successfully"),i==="stdio"?(await h.start({transportType:"stdio"}),u("\u2713 FastMCP server running with stdio transport")):(await h.start({transportType:"httpStream",httpStream:{port:t.port||3e3,endpoint:t.endpoint||"/mcp"}}),u(`\u2713 FastMCP server running on http://0.0.0.0:${t.port||3e3}${t.endpoint||"/mcp"}`),u("\u{1F50C} Connect with StreamableHTTPClientTransport")),process.on("SIGINT",async()=>{u("Received SIGINT, closing server..."),await s.close(),process.exit(0)}),process.on("SIGTERM",async()=>{u("Received SIGTERM, closing server..."),await s.close(),process.exit(0)})}export{J as a,Y as b};
48
- //# sourceMappingURL=chunk-TAP5LWZ7.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// Polyfill for Web Crypto API in Node.js environments\nimport { webcrypto } from \"crypto\"\n\nif (!globalThis.crypto) {\n globalThis.crypto = webcrypto as Crypto\n}\n\nimport { FastMCP } from \"@jordanburke/fastmcp\"\nimport { createHash, randomBytes } from \"crypto\"\nimport { createRequire } from \"module\"\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require(\"../package.json\") as { version: string }\nimport * as jwt from \"jsonwebtoken\"\nimport { URL } from \"url\"\nimport { z } from \"zod\"\n\nimport { DuckPondServer, type DuckPondServerConfig } from \"./server-core\"\nimport {\n detachUserSchema,\n executeSchema,\n getUserStatsSchema,\n isAttachedSchema,\n listUsersSchema,\n querySchema,\n} from \"./tools\"\nimport { loggers } from \"./utils/logger\"\n\nconst log = loggers.fastmcp\n\nexport type OAuthConfig = {\n enabled: boolean\n username: string\n password: string\n userId: string\n email?: string\n issuer?: string\n resource?: string\n}\n\nexport type FastMCPServerOptions = {\n config: DuckPondServerConfig\n port?: number\n endpoint?: string\n oauth?: OAuthConfig\n basicAuth?: {\n username: string\n password: string\n userId?: string\n email?: string\n }\n}\n\n// JWT secret for token signing/validation\nconst JWT_SECRET = process.env.DUCKPOND_JWT_SECRET || randomBytes(32).toString(\"hex\")\n\n// JWT token expiration configuration (default: 1 year)\nconst JWT_EXPIRES_IN = process.env.DUCKPOND_JWT_EXPIRES_IN\n ? parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN, 10)\n : 365 * 24 * 60 * 60 // 1 year in seconds\n\n// In-memory stores for OAuth flow\nconst authorizationCodes = new Map<\n string,\n {\n createdAt: number\n redirectUri?: string\n codeChallenge?: string\n codeChallengeMethod?: string\n userId: string\n }\n>()\n\nconst refreshTokens = new Map<\n string,\n {\n createdAt: number\n userId: string\n email?: string\n }\n>()\n\n// AuthSession type for FastMCP authentication\ntype AuthSession = {\n userId: string\n email: string\n scope: string\n [key: string]: unknown // Allow additional properties\n}\n\ntype OAuthClientRegistrationRequest = {\n grant_types?: string[]\n response_types?: string[]\n redirect_uris?: string[]\n token_endpoint_auth_method?: string\n client_name?: string\n scope?: string\n}\n\ntype OAuthClientRegistrationResponse = {\n client_id: string\n client_secret: string\n client_id_issued_at: number\n client_secret_expires_at: number\n grant_types: string[]\n response_types: string[]\n redirect_uris: string[]\n token_endpoint_auth_method: string\n client_name?: string\n scope?: string\n}\n\nexport function createFastMCPServer(options: FastMCPServerOptions): {\n server: FastMCP\n duckpond: DuckPondServer\n} {\n log(\"🚀 Initializing FastMCP server...\")\n\n // Create DuckPond server instance\n const duckpond = new DuckPondServer(options.config)\n\n // Build server configuration\n const baseConfig = {\n name: \"duckpond\",\n version: packageJson.version as `${number}.${number}.${number}`,\n health: {\n enabled: true,\n path: \"/health\",\n status: 200,\n message: JSON.stringify({\n status: \"healthy\",\n service: \"duckpond-mcp-server\",\n version: packageJson.version,\n timestamp: new Date().toISOString(),\n }),\n },\n }\n\n // Create server with authentication (OAuth, Basic Auth, or none)\n const server =\n options.oauth?.enabled || options.basicAuth\n ? new FastMCP<AuthSession>({\n ...baseConfig,\n oauth: {\n enabled: true,\n authorizationServer: {\n issuer: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n authorizationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/authorize`,\n tokenEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/token`,\n jwksUri: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/jwks`,\n registrationEndpoint: `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/oauth/register`,\n responseTypesSupported: [\"code\"],\n grantTypesSupported: [\"authorization_code\"],\n tokenEndpointAuthMethodsSupported: [\"client_secret_post\", \"client_secret_basic\"],\n codeChallengeMethodsSupported: [\"S256\", \"plain\"],\n },\n protectedResource: {\n resource:\n process.env.DUCKPOND_OAUTH_RESOURCE ||\n options.oauth?.resource ||\n `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n authorizationServers: [options.oauth?.issuer || `http://localhost:${options.port || 3000}`],\n },\n },\n authenticate: (request) => {\n const authHeader = request.headers?.authorization\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n // For OAuth-enabled servers, require authentication\n if (!authHeader) {\n if (options.oauth?.enabled) {\n // Return HTTP 401 with WWW-Authenticate header for proper OAuth discovery\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required. Please authenticate via OAuth.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n }\n\n // For non-OAuth servers, also require some form of auth\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Authorization required.\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n )\n }\n\n // Handle Basic Authentication\n if (options.basicAuth && authHeader.startsWith(\"Basic \")) {\n const credentials = Buffer.from(authHeader.slice(6), \"base64\").toString(\"utf-8\")\n const [username, password] = credentials.split(\":\")\n\n if (username === options.basicAuth.username && password === options.basicAuth.password) {\n return Promise.resolve({\n userId: options.basicAuth.userId || username,\n email: options.basicAuth.email || `${username}@example.com`,\n scope: \"read write\",\n })\n } else {\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid username or password\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Basic realm=\"MCP\"`,\n },\n },\n )\n }\n }\n\n // Handle Bearer Token (OAuth) - Validate JWT\n if (options.oauth?.enabled && authHeader.startsWith(\"Bearer \")) {\n const token = authHeader.slice(7) // Remove 'Bearer ' prefix\n\n try {\n // Verify JWT token\n const decoded = jwt.verify(token, JWT_SECRET) as jwt.JwtPayload\n\n if (!decoded.sub || !decoded.iat || !decoded.exp) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid token structure\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid token structure\"`,\n },\n },\n )\n }\n\n // Validate audience\n const expectedAudience = options.oauth?.resource || `${baseUrl}/mcp`\n if (decoded.aud && decoded.aud !== expectedAudience) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Token audience mismatch\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Token audience mismatch\"`,\n },\n },\n )\n }\n\n // Return user info from JWT claims\n return Promise.resolve({\n userId: decoded.sub,\n email: (decoded.email as string) || \"\",\n scope: (decoded.scope as string) || \"read write\",\n })\n } catch (error) {\n if (error instanceof Response) {\n throw error // Re-throw our custom Response errors\n }\n\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid or expired token\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", error=\"invalid_token\", error_description=\"Invalid or expired token\"`,\n },\n },\n )\n }\n }\n\n throw new Response(\n JSON.stringify({\n error: \"unauthorized\",\n error_description: \"Invalid authorization header format\",\n }),\n {\n status: 401,\n statusText: \"Unauthorized\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": `Bearer realm=\"MCP\", authorization_uri=\"${baseUrl}/oauth/authorize\", resource=\"${baseUrl}/.well-known/oauth-protected-resource\"`,\n },\n },\n )\n },\n })\n : new FastMCP(baseConfig)\n\n // Add query tool\n server.addTool({\n name: \"query\",\n description: \"Execute a SQL query for a specific user and return results\",\n parameters: querySchema,\n execute: async (args) => {\n try {\n const result = await duckpond.query(args.userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n rows: result.data,\n rowCount: result.data.length,\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in query tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add execute tool\n server.addTool({\n name: \"execute\",\n description: \"Execute SQL statement (DDL/DML) for a specific user without returning results\",\n parameters: executeSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.execute(args.userId, args.sql)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: \"Statement executed successfully\",\n executionTime: result.executionTime,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in execute tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add getUserStats tool\n server.addTool({\n name: \"getUserStats\",\n description: \"Get statistics about a user's database (memory usage, query count, etc.)\",\n parameters: getUserStatsSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.getUserStats(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n ...result.data,\n lastAccess: result.data.lastAccess.toISOString(),\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in getUserStats tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add isAttached tool\n server.addTool({\n name: \"isAttached\",\n description: \"Check if a user's database is currently cached in memory\",\n parameters: isAttachedSchema,\n execute: async (args) => {\n try {\n const result = duckpond.isAttached(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n attached: result.data,\n userId: args.userId,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in isAttached tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add detachUser tool\n server.addTool({\n name: \"detachUser\",\n description: \"Manually detach a user's database from the cache to free resources\",\n parameters: detachUserSchema,\n execute: async (args) => {\n try {\n const result = await duckpond.detachUser(args.userId)\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(\n {\n success: true,\n message: `User ${args.userId} detached successfully`,\n },\n null,\n 2,\n )\n } catch (error) {\n log(\"Error in detachUser tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add listUsers tool\n server.addTool({\n name: \"listUsers\",\n description: \"List all currently cached users and cache statistics\",\n parameters: listUsersSchema,\n execute: async () => {\n try {\n const result = duckpond.listUsers()\n\n if (!result.success) {\n return `ERROR: ${result.error.message}`\n }\n\n return JSON.stringify(result.data, null, 2)\n } catch (error) {\n log(\"Error in listUsers tool:\", error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n return `ERROR: ${JSON.stringify({ error: errorMessage }, null, 2)}`\n }\n },\n })\n\n // Add OAuth flow endpoints if OAuth is enabled\n if (options.oauth?.enabled) {\n setupOAuthEndpoints(server, options)\n }\n\n // Add root info endpoint using Hono\n const app = server.getApp()\n app.get(\"/\", (c) => {\n const baseUrl = options.oauth?.issuer || `http://localhost:${options.port || 3000}`\n\n const serverInfo = {\n name: \"DuckPond MCP Server\",\n version: packageJson.version,\n description: \"Model Context Protocol server for multi-tenant DuckDB with R2/S3 storage\",\n service: \"duckpond-mcp-server\",\n capabilities: {\n tools: [\"query\", \"execute\", \"getUserStats\", \"isAttached\", \"detachUser\", \"listUsers\"],\n transports: [\"stdio\", \"http\"],\n authentication: {\n oauth: options.oauth?.enabled || false,\n basicAuth: !!options.basicAuth,\n },\n },\n endpoints: {\n mcp: `${baseUrl}${options.endpoint || \"/mcp\"}`,\n health: `${baseUrl}/health`,\n ...(options.oauth?.enabled && {\n oauth: {\n authorization: `${baseUrl}/oauth/authorize`,\n token: `${baseUrl}/oauth/token`,\n jwks: `${baseUrl}/oauth/jwks`,\n register: `${baseUrl}/oauth/register`,\n },\n }),\n },\n timestamp: new Date().toISOString(),\n }\n\n return c.json(serverInfo)\n })\n\n log(\"✓ FastMCP server created\")\n\n return { server, duckpond }\n}\n\nfunction setupOAuthEndpoints(server: FastMCP, options: FastMCPServerOptions): void {\n const app = server.getApp()\n\n // Clean up old codes and refresh tokens every minute\n setInterval(() => {\n const now = Date.now()\n // Clean authorization codes (10 minutes)\n for (const [code, data] of authorizationCodes.entries()) {\n if (now - data.createdAt > 600000) {\n authorizationCodes.delete(code)\n }\n }\n // Clean refresh tokens (30 days)\n for (const [token, data] of refreshTokens.entries()) {\n if (now - data.createdAt > 2592000000) {\n refreshTokens.delete(token)\n }\n }\n }, 60000)\n\n // OAuth Authorization Endpoint - Login Form\n app.get(\"/oauth/authorize\", (c) => {\n const params = c.req.query()\n const responseType = params.response_type\n const redirectUri = params.redirect_uri\n const state = params.state\n const codeChallenge = params.code_challenge\n const codeChallengeMethod = params.code_challenge_method\n const clientId = params.client_id\n\n if (responseType !== \"code\") {\n return c.json(\n {\n error: \"unsupported_response_type\",\n error_description: \"Only 'code' response type is supported\",\n },\n 400,\n )\n }\n\n if (!redirectUri) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"redirect_uri is required\",\n },\n 400,\n )\n }\n\n // Validate PKCE parameters if present\n if (codeChallenge) {\n if (!codeChallengeMethod || ![\"S256\", \"plain\"].includes(codeChallengeMethod)) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Invalid code_challenge_method. Only 'S256' and 'plain' are supported\",\n },\n 400,\n )\n }\n }\n\n // Serve login form\n const loginForm = `\n<!DOCTYPE html>\n<html>\n<head>\n <title>OAuth Login - DuckPond MCP Server</title>\n <style>\n body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }\n .form-group { margin-bottom: 15px; }\n label { display: block; margin-bottom: 5px; font-weight: bold; }\n input[type=\"text\"], input[type=\"password\"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }\n button { width: 100%; padding: 12px; background: #007cba; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }\n button:hover { background: #005a87; }\n .app-info { background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 20px; }\n </style>\n</head>\n<body>\n <div class=\"app-info\">\n <h3>🔐 OAuth Authorization</h3>\n <p><strong>Application:</strong> ${clientId || \"MCP Client\"}</p>\n <p><strong>Permissions:</strong> Read and write access to DuckDB databases</p>\n </div>\n\n <form method=\"POST\" action=\"/oauth/authorize\">\n <input type=\"hidden\" name=\"response_type\" value=\"${responseType}\">\n <input type=\"hidden\" name=\"redirect_uri\" value=\"${redirectUri}\">\n <input type=\"hidden\" name=\"state\" value=\"${state || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge\" value=\"${codeChallenge || \"\"}\">\n <input type=\"hidden\" name=\"code_challenge_method\" value=\"${codeChallengeMethod || \"\"}\">\n <input type=\"hidden\" name=\"client_id\" value=\"${clientId || \"\"}\">\n\n <div class=\"form-group\">\n <label for=\"username\">Username:</label>\n <input type=\"text\" id=\"username\" name=\"username\" required>\n </div>\n\n <div class=\"form-group\">\n <label for=\"password\">Password:</label>\n <input type=\"password\" id=\"password\" name=\"password\" required>\n </div>\n\n <button type=\"submit\">Authorize Application</button>\n </form>\n</body>\n</html>`\n\n return c.html(loginForm)\n })\n\n // OAuth Authorization POST - Process Login\n app.post(\"/oauth/authorize\", async (c) => {\n try {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n\n const username = params.get(\"username\")\n const password = params.get(\"password\")\n const redirectUri = params.get(\"redirect_uri\")\n const state = params.get(\"state\")\n const codeChallenge = params.get(\"code_challenge\")\n const codeChallengeMethod = params.get(\"code_challenge_method\")\n\n // Validate credentials\n if (username !== options.oauth?.username || password !== options.oauth?.password) {\n const errorForm = `\n<!DOCTYPE html>\n<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>\n<body><div class=\"error\">❌ Invalid username or password</div><a href=\"javascript:history.back()\">← Try Again</a></body></html>`\n return c.html(errorForm, 401)\n }\n\n // Generate authorization code\n const code = randomBytes(16).toString(\"hex\")\n authorizationCodes.set(code, {\n createdAt: Date.now(),\n redirectUri: redirectUri || \"\",\n codeChallenge: codeChallenge || undefined,\n codeChallengeMethod: codeChallengeMethod || undefined,\n userId: options.oauth?.userId || username || \"oauth-user\",\n })\n\n // Redirect with authorization code\n const redirectUrl = new URL(redirectUri || \"\")\n redirectUrl.searchParams.set(\"code\", code)\n if (state) {\n redirectUrl.searchParams.set(\"state\", state)\n }\n\n return c.redirect(redirectUrl.toString(), 302)\n } catch {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"Failed to process authorization request\",\n },\n 400,\n )\n }\n })\n\n // OAuth Token Endpoint\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.text()\n const params = new URLSearchParams(body)\n const grantType = params.get(\"grant_type\")\n const code = params.get(\"code\")\n const redirectUri = params.get(\"redirect_uri\")\n const codeVerifier = params.get(\"code_verifier\")\n const refreshTokenParam = params.get(\"refresh_token\")\n\n if (grantType === \"refresh_token\") {\n // Handle refresh token flow\n if (!refreshTokenParam) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description: \"refresh_token is required for refresh_token grant type\",\n },\n 400,\n )\n }\n\n const tokenData = refreshTokens.get(refreshTokenParam)\n if (!tokenData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired refresh token\",\n },\n 400,\n )\n }\n\n // Remove old refresh token (token rotation)\n refreshTokens.delete(refreshTokenParam)\n\n // Generate new JWT access token\n const accessTokenPayload = {\n sub: tokenData.userId,\n email: tokenData.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate new refresh token\n const newRefreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(newRefreshToken, {\n createdAt: Date.now(),\n userId: tokenData.userId,\n email: tokenData.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: newRefreshToken,\n })\n }\n\n if (grantType !== \"authorization_code\") {\n return c.json(\n {\n error: \"unsupported_grant_type\",\n error_description: \"Only 'authorization_code' and 'refresh_token' grant types are supported\",\n },\n 400,\n )\n }\n\n const codeData = authorizationCodes.get(code || \"\")\n if (!codeData) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid or expired authorization code\",\n },\n 400,\n )\n }\n\n // Validate redirect_uri matches\n if (codeData.redirectUri && codeData.redirectUri !== redirectUri) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"redirect_uri mismatch\",\n },\n 400,\n )\n }\n\n // Validate PKCE if code_challenge was provided\n if (codeData.codeChallenge) {\n if (!codeVerifier) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"code_verifier is required when code_challenge was used\",\n },\n 400,\n )\n }\n\n let expectedChallenge: string\n if (codeData.codeChallengeMethod === \"S256\") {\n expectedChallenge = createHash(\"sha256\").update(codeVerifier).digest().toString(\"base64url\")\n } else {\n // 'plain' method\n expectedChallenge = codeVerifier\n }\n\n if (expectedChallenge !== codeData.codeChallenge) {\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"Invalid code_verifier\",\n },\n 400,\n )\n }\n }\n\n // Remove used code\n authorizationCodes.delete(code!)\n\n // Generate JWT access token\n const accessTokenPayload = {\n sub: codeData.userId,\n email: options.oauth?.email || \"\",\n scope: \"read write\",\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + JWT_EXPIRES_IN,\n iss: options.oauth?.issuer || `http://localhost:${options.port || 3000}`,\n aud: options.oauth?.resource || `${options.oauth?.issuer || `http://localhost:${options.port || 3000}`}/mcp`,\n }\n\n // Generate refresh token\n const refreshToken = randomBytes(32).toString(\"hex\")\n refreshTokens.set(refreshToken, {\n createdAt: Date.now(),\n userId: codeData.userId,\n email: options.oauth?.email,\n })\n\n const accessToken = jwt.sign(accessTokenPayload, JWT_SECRET)\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: JWT_EXPIRES_IN,\n scope: \"read write\",\n refresh_token: refreshToken,\n })\n })\n\n // JWKS Endpoint\n app.get(\"/oauth/jwks\", (c) => {\n return c.json({\n keys: [\n {\n kty: \"oct\", // Octet sequence for symmetric keys\n use: \"sig\",\n kid: \"duckpond-hmac-key\",\n alg: \"HS256\",\n },\n ],\n })\n })\n\n // Dynamic Client Registration\n app.post(\"/oauth/register\", async (c) => {\n try {\n let registrationRequest: OAuthClientRegistrationRequest = {}\n\n try {\n const body = await c.req.text()\n if (body && body !== \"[object Object]\") {\n try {\n registrationRequest = JSON.parse(body) as OAuthClientRegistrationRequest\n } catch {\n const formData = Object.fromEntries(new URLSearchParams(body))\n registrationRequest = formData as OAuthClientRegistrationRequest\n }\n }\n } catch (parseError) {\n log(\"Error parsing request body:\", parseError)\n }\n\n const clientId = `client-${randomBytes(8).toString(\"hex\")}`\n const clientSecret = randomBytes(16).toString(\"hex\")\n\n const response: OAuthClientRegistrationResponse = {\n client_id: clientId,\n client_secret: clientSecret,\n client_id_issued_at: Math.floor(Date.now() / 1000),\n client_secret_expires_at: 0, // Never expires\n grant_types: registrationRequest.grant_types || [\"authorization_code\"],\n response_types: registrationRequest.response_types || [\"code\"],\n redirect_uris: registrationRequest.redirect_uris || [],\n token_endpoint_auth_method: registrationRequest.token_endpoint_auth_method || \"client_secret_post\",\n }\n\n if (registrationRequest.client_name) {\n response.client_name = registrationRequest.client_name\n }\n if (registrationRequest.scope) {\n response.scope = registrationRequest.scope\n }\n\n return c.json(response, 201)\n } catch (error) {\n return c.json(\n {\n error: \"invalid_client_metadata\",\n error_description:\n \"Invalid client registration request: \" + (error instanceof Error ? error.message : String(error)),\n },\n 400,\n )\n }\n })\n\n log(\"✓ OAuth flow endpoints added\")\n}\nexport async function startServer(options: FastMCPServerOptions, transport: \"stdio\" | \"http\"): Promise<void> {\n const { server, duckpond } = createFastMCPServer(options)\n\n // Initialize DuckPond\n const initResult = await duckpond.init()\n if (!initResult.success) {\n throw new Error(`Failed to initialize DuckPond: ${initResult.error.message}`)\n }\n\n log(\"DuckPond initialized successfully\")\n\n // Start the server with appropriate transport\n if (transport === \"stdio\") {\n await server.start({\n transportType: \"stdio\",\n })\n log(\"✓ FastMCP server running with stdio transport\")\n } else {\n await server.start({\n transportType: \"httpStream\",\n httpStream: {\n port: options.port || 3000,\n endpoint: (options.endpoint || \"/mcp\") as `/${string}`,\n },\n })\n log(`✓ FastMCP server running on http://0.0.0.0:${options.port || 3000}${options.endpoint || \"/mcp\"}`)\n log(\"🔌 Connect with StreamableHTTPClientTransport\")\n }\n\n // Handle cleanup on exit\n process.on(\"SIGINT\", async () => {\n log(\"Received SIGINT, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n\n process.on(\"SIGTERM\", async () => {\n log(\"Received SIGTERM, closing server...\")\n await duckpond.close()\n process.exit(0)\n })\n}\n"],"mappings":"2JACA,OAAS,aAAAA,MAAiB,SAM1B,OAAS,WAAAC,MAAe,uBACxB,OAAS,cAAAC,EAAY,eAAAC,MAAmB,SACxC,OAAS,iBAAAC,MAAqB,SAI9B,UAAYC,MAAS,eACrB,OAAS,OAAAC,MAAW,MAXf,WAAW,SACd,WAAW,OAASC,GAOtB,IAAMC,EAAUC,EAAc,YAAY,GAAG,EACvCC,EAAcF,EAAQ,iBAAiB,EAgBvCG,EAAMC,EAAQ,QA0BdC,EAAa,QAAQ,IAAI,qBAAuBC,EAAY,EAAE,EAAE,SAAS,KAAK,EAG9EC,EAAiB,QAAQ,IAAI,wBAC/B,SAAS,QAAQ,IA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,oDAA+C,IAEnD,MAAMY,EAAO,MAAM,CACjB,cAAe,aACf,WAAY,CACV,KAAMJ,EAAQ,MAAQ,IACtB,SAAWA,EAAQ,UAAY,MACjC,CACF,CAAC,EACDR,EAAI,mDAA8CQ,EAAQ,MAAQ,GAAI,GAAGA,EAAQ,UAAY,MAAM,EAAE,EACrGR,EAAI,sDAA+C,GAIrD,QAAQ,GAAG,SAAU,SAAY,CAC/BA,EAAI,oCAAoC,EACxC,MAAMS,EAAS,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,GAAG,UAAW,SAAY,CAChCT,EAAI,qCAAqC,EACzC,MAAMS,EAAS,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH","names":["webcrypto","FastMCP","createHash","randomBytes","createRequire","jwt","URL","webcrypto","require","createRequire","packageJson","log","loggers","JWT_SECRET","randomBytes","JWT_EXPIRES_IN","authorizationCodes","refreshTokens","createFastMCPServer","options","duckpond","DuckPondServer","baseConfig","server","FastMCP","request","authHeader","baseUrl","credentials","username","password","token","decoded","expectedAudience","error","querySchema","args","result","errorMessage","executeSchema","getUserStatsSchema","isAttachedSchema","detachUserSchema","listUsersSchema","setupOAuthEndpoints","c","serverInfo","app","now","code","data","params","responseType","redirectUri","state","codeChallenge","codeChallengeMethod","clientId","loginForm","body","redirectUrl","URL","grantType","codeVerifier","refreshTokenParam","tokenData","accessTokenPayload","newRefreshToken","accessToken","codeData","expectedChallenge","createHash","refreshToken","registrationRequest","parseError","clientSecret","response","startServer","transport","initResult"]}