duckpond-mcp-server 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/defineProperty-BEGP2H1W.js +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib.d.ts +2 -2
- package/dist/lib.js +1 -1
- package/dist/server-core.d.ts +1 -3
- package/dist/server-core.js +2 -1
- package/dist/server-core.js.map +1 -0
- package/dist/server.d.ts +29 -2
- package/dist/server.js +2 -2
- package/dist/server.js.map +1 -1
- package/dist/tools/index.d.ts +6 -31
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/ui-server.js +2 -1
- package/dist/ui-server.js.map +1 -0
- package/dist/utils/logger.js +2 -1
- package/dist/utils/logger.js.map +1 -0
- package/package.json +11 -11
- package/dist/logger-CX5FKgvo.js +0 -2
- package/dist/logger-CX5FKgvo.js.map +0 -1
- package/dist/server-core-B66uY2zm.js +0 -2
- package/dist/server-core-B66uY2zm.js.map +0 -1
- package/dist/ui-server-BoQ-kekq.js +0 -2
- package/dist/ui-server-BoQ-kekq.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}function t(t,n){if(e(t)!=`object`||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,n||`default`);if(e(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(t)}function n(n){var r=t(n,`string`);return e(r)==`symbol`?r:r+``}function r(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}export{r as t};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{loggers as e}from"./utils/logger.js";import{getDefaultUserId as t}from"./tools/index.js";import{startServer as n}from"./server.js";import{webcrypto as r}from"crypto";import{Command as i}from"commander";import{createRequire as a}from"module";globalThis.crypto||(globalThis.crypto=r);const o=a(import.meta.url)(`../package.json`),s=e.main;function c(e){return e.startsWith(`~/`)?`${process.env.HOME||process.env.USERPROFILE||`.`}${e.slice(1)}`:e}function l(){return`${process.env.HOME||process.env.USERPROFILE||`.`}/.duckpond/data`}function u(){let e=c(process.env.DUCKPOND_DATA_DIR||l()),t={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||`duckdb`,tempDir:process.env.DUCKPOND_TEMP_DIR,cacheDir:process.env.DUCKPOND_CACHE_DIR||e,dataDir:e};return process.env.DUCKPOND_R2_ACCOUNT_ID&&(t.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&&(t.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&&(t.s3.endpoint=process.env.DUCKPOND_S3_ENDPOINT)),t}const d=new i;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`).option(`--ui`,`Enable DuckDB UI (auto-starts for DUCKPOND_DEFAULT_USER)`).option(`--ui-port <port>`,`UI management server port, only used when no default user (default: 4000)`,`4000`).option(`--ui-internal-port <port>`,`DuckDB UI port (default: 4213)`,`4213`).action(async e=>{try{let r=u(),i=t();s(`Starting DuckPond MCP Server with ${e.transport} transport`),s(`Configuration:`,{memoryLimit:r.memoryLimit,threads:r.threads,maxActiveUsers:r.maxActiveUsers,strategy:r.strategy,dataDir:r.dataDir,tempDir:r.tempDir,cacheDir:r.cacheDir,cacheType:r.cacheType,hasR2:!!r.r2,hasS3:!!r.s3,defaultUser:i||`(not set)`}),r.r2?console.error(`☁️ Storage: Cloudflare R2`):r.s3?console.error(`☁️ Storage: AWS S3`):console.error(`💾 Storage: Local disk (${r.dataDir})`),i&&console.error(`👤 Default user: ${i}`);let a;if(process.env.DUCKPOND_OAUTH_ENABLED===`true`){let t=process.env.DUCKPOND_OAUTH_USERNAME,n=process.env.DUCKPOND_OAUTH_PASSWORD;(!t||!n)&&(console.error(`❌ OAuth enabled but DUCKPOND_OAUTH_USERNAME and DUCKPOND_OAUTH_PASSWORD are required`),process.exit(1)),a={enabled:!0,username:t,password:n,userId:process.env.DUCKPOND_OAUTH_USER_ID||t,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(`🔐 OAuth enabled with username/password authentication`),console.error(` Username: ${a.username}`),console.error(` User ID: ${a.userId}`),console.error(` ✓ Login form will be shown at authorization endpoint`)}let o;process.env.DUCKPOND_BASIC_AUTH_USERNAME&&process.env.DUCKPOND_BASIC_AUTH_PASSWORD&&(o={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(`🔐 Basic authentication enabled`),console.error(` Username: ${o.username}`),console.error(` User ID: ${o.userId||o.username}`));let c=e.ui||process.env.DUCKPOND_UI_ENABLED===`true`,l=parseInt(e.uiPort)||4e3,d=parseInt(e.uiInternalPort)||4213;c&&e.transport===`stdio`&&(i?console.error(`🖥️ DuckDB UI will start at http://localhost:${d}`):(console.error(`🖥️ UI management server at http://localhost:${l}/ui`),console.error(` Visit /ui/:userId to start DuckDB UI for a user`))),e.transport===`stdio`||e.transport===`http`?await n({config:r,port:parseInt(e.port)||3e3,endpoint:`/mcp`,oauth:a,basicAuth:o,ui:c?{enabled:!0,port:l,internalPort:d,autoStartUser:i}:void 0},e.transport===`stdio`?`stdio`:`http`):(s(`Unknown transport: ${e.transport}`),process.exit(1))}catch(e){s(`Fatal error:`,e),console.error(`Fatal error:`,e),process.exit(1)}}),d.parse();export{};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["config: DuckPondServerConfig","oauthConfig: OAuthConfig | undefined","basicAuthConfig: { username: string; password: string; userId?: string; email?: string } | undefined"],"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 * Expand ~ to home directory in paths\n */\nfunction expandTilde(path: string): string {\n if (path.startsWith(\"~/\")) {\n const home = process.env.HOME || process.env.USERPROFILE || \".\"\n return `${home}${path.slice(1)}`\n }\n return path\n}\n\n/**\n * Get the default data directory for persistent storage\n */\nfunction getDefaultDataDir(): string {\n const home = process.env.HOME || process.env.USERPROFILE || \".\"\n return `${home}/.duckpond/data`\n}\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n // Default to local disk storage (expand ~ if present)\n const dataDir = expandTilde(process.env.DUCKPOND_DATA_DIR || getDefaultDataDir())\n\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\") || \"duckdb\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR || dataDir,\n dataDir,\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 (auto-starts for DUCKPOND_DEFAULT_USER)\")\n .option(\"--ui-port <port>\", \"UI management server port, only used when no default user (default: 4000)\", \"4000\")\n .option(\"--ui-internal-port <port>\", \"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 dataDir: config.dataDir,\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 // Log storage mode\n if (config.r2) {\n console.error(\"☁️ Storage: Cloudflare R2\")\n } else if (config.s3) {\n console.error(\"☁️ Storage: AWS S3\")\n } else {\n console.error(`💾 Storage: Local disk (${config.dataDir})`)\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 if (defaultUser) {\n // Will auto-start UI for default user - show where to access it\n console.error(`🖥️ DuckDB UI will start at http://localhost:${uiInternalPort}`)\n } else {\n // No default user - management server needed\n console.error(`🖥️ UI management server at http://localhost:${uiPort}/ui`)\n console.error(` Visit /ui/:userId to start DuckDB UI for a user`)\n }\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 autoStartUser: defaultUser,\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":";uTAKK,WAAW,SACd,WAAW,OAAS,GAUtB,MAAM,EADU,EAAc,OAAO,KAAK,IAAI,CAClB,kBAAkB,CAMxC,EAAM,EAAQ,KAKpB,SAAS,EAAY,EAAsB,CAKzC,OAJI,EAAK,WAAW,KAAK,CAEhB,GADM,QAAQ,IAAI,MAAQ,QAAQ,IAAI,aAAe,MAC3C,EAAK,MAAM,EAAE,GAEzB,EAMT,SAAS,GAA4B,CAEnC,MAAO,GADM,QAAQ,IAAI,MAAQ,QAAQ,IAAI,aAAe,IAC7C,iBAMjB,SAAS,GAAyC,CAEhD,IAAM,EAAU,EAAY,QAAQ,IAAI,mBAAqB,GAAmB,CAAC,CAE3EA,EAA+B,CACnC,YAAa,QAAQ,IAAI,uBAAyB,MAClD,QAAS,SAAS,QAAQ,IAAI,kBAAoB,IAAI,CACtD,eAAgB,SAAS,QAAQ,IAAI,2BAA6B,KAAK,CACvE,gBAAiB,SAAS,QAAQ,IAAI,2BAA6B,SAAS,CAC5E,UAAY,QAAQ,IAAI,qBAAsD,OAC9E,SAAW,QAAQ,IAAI,mBAAyD,SAChF,QAAS,QAAQ,IAAI,kBACrB,SAAU,QAAQ,IAAI,oBAAsB,EAC5C,UACD,CA0BD,OAvBI,QAAQ,IAAI,yBACd,EAAO,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AM,EACN,aAAc,EACd,cAAe,EAChB,CACD,IAAA,GACL,CACD,EAAQ,YAAc,QAAU,QAAU,OAC3C,EAED,EAAI,sBAAsB,EAAQ,YAAY,CAC9C,QAAQ,KAAK,EAAE,QAEV,EAAO,CACd,EAAI,eAAgB,EAAM,CAC1B,QAAQ,MAAM,eAAgB,EAAM,CACpC,QAAQ,KAAK,EAAE,GAEjB,CAEJ,EAAQ,OAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"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 * Expand ~ to home directory in paths\n */\nfunction expandTilde(path: string): string {\n if (path.startsWith(\"~/\")) {\n const home = process.env.HOME || process.env.USERPROFILE || \".\"\n return `${home}${path.slice(1)}`\n }\n return path\n}\n\n/**\n * Get the default data directory for persistent storage\n */\nfunction getDefaultDataDir(): string {\n const home = process.env.HOME || process.env.USERPROFILE || \".\"\n return `${home}/.duckpond/data`\n}\n\n/**\n * Parse environment variables into DuckPond configuration\n */\nfunction getConfigFromEnv(): DuckPondServerConfig {\n // Default to local disk storage (expand ~ if present)\n const dataDir = expandTilde(process.env.DUCKPOND_DATA_DIR || getDefaultDataDir())\n\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\") || \"duckdb\",\n tempDir: process.env.DUCKPOND_TEMP_DIR,\n cacheDir: process.env.DUCKPOND_CACHE_DIR || dataDir,\n dataDir,\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 (auto-starts for DUCKPOND_DEFAULT_USER)\")\n .option(\"--ui-port <port>\", \"UI management server port, only used when no default user (default: 4000)\", \"4000\")\n .option(\"--ui-internal-port <port>\", \"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 dataDir: config.dataDir,\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 // Log storage mode\n if (config.r2) {\n console.error(\"☁️ Storage: Cloudflare R2\")\n } else if (config.s3) {\n console.error(\"☁️ Storage: AWS S3\")\n } else {\n console.error(`💾 Storage: Local disk (${config.dataDir})`)\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 if (defaultUser) {\n // Will auto-start UI for default user - show where to access it\n console.error(`🖥️ DuckDB UI will start at http://localhost:${uiInternalPort}`)\n } else {\n // No default user - management server needed\n console.error(`🖥️ UI management server at http://localhost:${uiPort}/ui`)\n console.error(` Visit /ui/:userId to start DuckDB UI for a user`)\n }\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 autoStartUser: defaultUser,\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":";wPAKK,WAAW,SACd,WAAW,OAAS,GAUtB,MAAM,EADU,EAAc,OAAO,KAAK,IAAI,CAClB,kB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BAAgC,QAAQ,IAAI,+BAC1D,EAAkB,CAChB,SAAU,QAAQ,IAAI,6BACtB,SAAU,QAAQ,IAAI,6BACtB,OAAQ,QAAQ,IAAI,4BACpB,MAAO,QAAQ,IAAI,0BACpB,CAED,QAAQ,MAAM,kCAAkC,CAChD,QAAQ,MAAM,gBAAgB,EAAgB,WAAW,CACzD,QAAQ,MAAM,eAAe,EAAgB,QAAU,EAAgB,WAAW,EAIpF,IAAM,EAAY,EAAQ,IAAM,QAAQ,IAAI,sBAAwB,OAC9D,EAAS,SAAS,EAAQ,OAAO,EAAI,IACrC,EAAiB,SAAS,EAAQ,eAAe,EAAI,KAEvD,GAAa,EAAQ,YAAc,UACjC,EAEF,QAAQ,MAAM,iDAAiD,IAAiB,EAGhF,QAAQ,MAAM,iDAAiD,EAAO,KAAK,CAC3E,QAAQ,MAAM,qDAAqD,GAKnE,EAAQ,YAAc,SAAW,EAAQ,YAAc,OACzD,MAAM,EACJ,CACE,SACA,KAAM,SAAS,EAAQ,KAAK,EAAI,IAChC,SAAU,OACV,MAAO,EACP,UAAW,EACX,GAAI,EACA,CACE,QAAS,GACT,KAAM,EACN,aAAc,EACd,cAAe,EAChB,CACD,IAAA,GACL,CACD,EAAQ,YAAc,QAAU,QAAU,OAC3C,EAED,EAAI,sBAAsB,EAAQ,YAAY,CAC9C,QAAQ,KAAK,EAAE,QAEV,EAAO,CACd,EAAI,eAAgB,EAAM,CAC1B,QAAQ,MAAM,eAAgB,EAAM,CACpC,QAAQ,KAAK,EAAE,GAEjB,CAEJ,EAAQ,OAAO"}
|
package/dist/lib.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { DuckPondServer, DuckPondServerConfig } from "./server-core.js";
|
|
2
|
-
import { FastMCPServerOptions, createFastMCPServer } from "./server.js";
|
|
2
|
+
import { FastMCPServerOptions, StartServerOptions, createFastMCPServer, startServer } from "./server.js";
|
|
3
3
|
import { getDefaultUserId } from "./tools/index.js";
|
|
4
|
-
export { DuckPondServer, type DuckPondServerConfig, type FastMCPServerOptions, createFastMCPServer, getDefaultUserId };
|
|
4
|
+
export { DuckPondServer, type DuckPondServerConfig, type FastMCPServerOptions, type StartServerOptions, createFastMCPServer, getDefaultUserId, startServer };
|
package/dist/lib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{getDefaultUserId as e}from"./tools/index.js";import{DuckPondServer as t}from"./server-core.js";import{createFastMCPServer as n,startServer as r}from"./server.js";export{t as DuckPondServer,n as createFastMCPServer,e as getDefaultUserId,r as startServer};
|
package/dist/server-core.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { DuckPondConfig, ErrorCode, UserStats } from "duckpond";
|
|
2
2
|
|
|
3
3
|
//#region src/server-core.d.ts
|
|
4
|
-
|
|
5
4
|
/**
|
|
6
5
|
* Result type for MCP tool responses
|
|
7
6
|
*/
|
|
@@ -26,8 +25,7 @@ type MCPResult<T> = {
|
|
|
26
25
|
* Extends DuckPondConfig with server-specific options
|
|
27
26
|
*/
|
|
28
27
|
type DuckPondServerConfig = DuckPondConfig & {
|
|
29
|
-
/** Directory for persistent database storage (default: ~/.duckpond/data) */
|
|
30
|
-
dataDir?: string;
|
|
28
|
+
/** Directory for persistent database storage (default: ~/.duckpond/data) */dataDir?: string;
|
|
31
29
|
};
|
|
32
30
|
/**
|
|
33
31
|
* Core DuckPond MCP Server
|
package/dist/server-core.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import"./logger-
|
|
1
|
+
import{loggers as e}from"./utils/logger.js";import{t}from"./defineProperty-BEGP2H1W.js";import{DuckPond as n}from"duckpond";const r=e.core;var i=class{constructor(e){this.config=e,t(this,`pond`,null),t(this,`initialized`,!1),t(this,`currentUIUserId`,null),t(this,`uiInternalPort`,4213),t(this,`uiKeepaliveTimer`,null),t(this,`UI_KEEPALIVE_INTERVAL`,3e4),r(`DuckPondServer created`)}async init(){if(this.initialized)return r(`Already initialized`),{success:!0,data:void 0};r(`Initializing DuckPond...`);let e=Date.now();this.pond=new n(this.config);let t=await this.pond.init();return this.handleEither(t,Date.now()-e)}async query(e,t){if(!this.pond)return this.notInitializedError();r(`Query for user ${e}: ${t.substring(0,100)}...`);let n=Date.now(),i=await this.pond.query(e,t);return this.handleEither(i,Date.now()-n)}async execute(e,t){if(!this.pond)return this.notInitializedError();r(`Execute for user ${e}: ${t.substring(0,100)}...`);let n=Date.now(),i=await this.pond.execute(e,t);return this.handleEither(i,Date.now()-n)}async getUserStats(e){if(!this.pond)return this.notInitializedError();r(`Getting stats for user ${e}`);let t=Date.now(),n=await this.pond.getUserStats(e);return this.handleEither(n,Date.now()-t)}isAttached(e){if(!this.pond)return this.notInitializedError();let t=this.pond.isAttached(e);return r(`User ${e} attached: ${t}`),{success:!0,data:t}}async detachUser(e){if(!this.pond)return this.notInitializedError();r(`Detaching user ${e}`);let t=Date.now(),n=await this.pond.detachUser(e);return this.handleEither(n,Date.now()-t)}listUsers(){if(!this.pond)return this.notInitializedError();r(`Listing cached users`);let e=this.pond.listUsers();return{success:!0,data:{users:e.users.toArray(),count:e.count,maxActiveUsers:e.maxActiveUsers,utilizationPercent:e.utilizationPercent}}}async close(){if(!this.pond)return{success:!0,data:void 0};r(`Closing DuckPond...`);let e=Date.now();this.currentUIUserId&&await this.stopUI();let t=await this.pond.close();return this.initialized=!1,this.pond=null,this.handleEither(t,Date.now()-e)}async startUI(e){if(!this.pond)return this.notInitializedError();r(`Starting UI for user ${e}`);let t=Date.now();if(this.currentUIUserId&&this.currentUIUserId!==e&&(r(`Stopping UI for previous user ${this.currentUIUserId}`),await this.stopUI()),this.currentUIUserId===e)return r(`UI already running for user ${e}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-t};let n=await this.execute(e,`INSTALL ui; LOAD ui;`);if(!n.success)return r(`Failed to install UI extension: ${n.error.message}`),n;let i=await this.execute(e,`SET ui_local_port = ${this.uiInternalPort}`);if(!i.success)return r(`Failed to set UI port: ${i.error.message}`),i;let a=await this.execute(e,`CALL start_ui_server()`);return a.success?(this.currentUIUserId=e,this.startUIKeepalive(e),r(`UI started for user ${e} on port ${this.uiInternalPort}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-t}):(r(`Failed to start UI server: ${a.error.message}`),a)}startUIKeepalive(e){this.stopUIKeepalive(),r(`Starting UI keepalive for user ${e}`),this.uiKeepaliveTimer=setInterval(async()=>{this.pond&&this.currentUIUserId===e&&(r(`UI keepalive ping for user ${e}`),await this.pond.query(e,`SELECT 1`))},this.UI_KEEPALIVE_INTERVAL)}stopUIKeepalive(){this.uiKeepaliveTimer&&(r(`Stopping UI keepalive`),clearInterval(this.uiKeepaliveTimer),this.uiKeepaliveTimer=null)}async stopUI(){if(this.stopUIKeepalive(),!this.currentUIUserId)return r(`No UI running to stop`),{success:!0,data:void 0};if(!this.pond)return this.currentUIUserId=null,{success:!0,data:void 0};r(`Stopping UI for user ${this.currentUIUserId}`);let e=Date.now(),t=await this.execute(this.currentUIUserId,`CALL stop_ui_server()`),n=this.currentUIUserId;return this.currentUIUserId=null,t.success?(r(`UI stopped for user ${n}`),{success:!0,data:void 0,executionTime:Date.now()-e}):(r(`Failed to stop UI: ${t.error.message}`),t)}getCurrentUIUser(){return this.currentUIUserId}setUIPort(e){this.uiInternalPort=e}getUIPort(){return this.uiInternalPort}handleEither(e,t){return e.fold(e=>({success:!1,error:{code:this.mapErrorCode(e.code),message:e.message,details:{originalCode:e.code,context:e.context,cause:e.cause?.message}}}),e=>({success:!0,data:e,executionTime:t}))}mapErrorCode(e){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`}[e]||`INTERNAL_ERROR`}notInitializedError(){return{success:!1,error:{code:`FAILED_PRECONDITION`,message:`DuckPond not initialized. Call init() first.`}}}};export{i as DuckPondServer};
|
|
2
|
+
//# sourceMappingURL=server-core.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-core.js","names":[],"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 * Extends DuckPondConfig with server-specific options\n */\nexport type DuckPondServerConfig = DuckPondConfig & {\n /** Directory for persistent database storage (default: ~/.duckpond/data) */\n dataDir?: string\n}\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 private uiKeepaliveTimer: ReturnType<typeof setInterval> | null = null\n private readonly UI_KEEPALIVE_INTERVAL = 30000 // 30 seconds\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 this.startUIKeepalive(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 * Start keepalive timer to prevent UI user from being evicted\n */\n private startUIKeepalive(userId: string): void {\n this.stopUIKeepalive()\n log(`Starting UI keepalive for user ${userId}`)\n this.uiKeepaliveTimer = setInterval(async () => {\n if (this.pond && this.currentUIUserId === userId) {\n log(`UI keepalive ping for user ${userId}`)\n await this.pond.query(userId, \"SELECT 1\")\n }\n }, this.UI_KEEPALIVE_INTERVAL)\n }\n\n /**\n * Stop the keepalive timer\n */\n private stopUIKeepalive(): void {\n if (this.uiKeepaliveTimer) {\n log(\"Stopping UI keepalive\")\n clearInterval(this.uiKeepaliveTimer)\n this.uiKeepaliveTimer = null\n }\n }\n\n /**\n * Stop the currently running DuckDB UI\n */\n async stopUI(): Promise<MCPResult<void>> {\n this.stopUIKeepalive()\n\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 as const,\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 as const,\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":"4HAKA,MAAM,EAAM,EAAQ,KAsCpB,IAAa,EAAb,KAA4B,CAQ1B,YA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DuckPondServerConfig } from "./server-core.js";
|
|
2
|
-
import { FastMCP } from "
|
|
2
|
+
import { FastMCP } from "fastmcp";
|
|
3
3
|
|
|
4
4
|
//#region src/server.d.ts
|
|
5
5
|
type OAuthConfig = {
|
|
@@ -33,7 +33,34 @@ declare function createFastMCPServer(options: FastMCPServerOptions): {
|
|
|
33
33
|
server: FastMCP;
|
|
34
34
|
duckpond: DuckPondServer;
|
|
35
35
|
};
|
|
36
|
+
type StartServerOptions = {
|
|
37
|
+
options: FastMCPServerOptions;
|
|
38
|
+
transport: "stdio" | "http"; /** Hook called after DuckPond init but before server start - use to register custom tools */
|
|
39
|
+
beforeStart?: (ctx: {
|
|
40
|
+
server: FastMCP;
|
|
41
|
+
duckpond: DuckPondServer;
|
|
42
|
+
}) => void | Promise<void>;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Start the DuckPond MCP server with full configuration
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* import { startServer, getDefaultUserId } from "duckpond-mcp-server/lib"
|
|
50
|
+
*
|
|
51
|
+
* await startServer({
|
|
52
|
+
* options: { config: { dataDir: "~/data" }, ui: { enabled: true, port: 4000, autoStartUser: "claude" } },
|
|
53
|
+
* transport: "stdio",
|
|
54
|
+
* beforeStart: async ({ server, duckpond }) => {
|
|
55
|
+
* // Register custom tools before server starts
|
|
56
|
+
* server.addTool({ name: "my_tool", ... })
|
|
57
|
+
* }
|
|
58
|
+
* })
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
declare function startServer(opts: StartServerOptions): Promise<void>;
|
|
62
|
+
/** @deprecated Use object form: startServer({ options, transport, beforeStart }) */
|
|
36
63
|
declare function startServer(options: FastMCPServerOptions, transport: "stdio" | "http"): Promise<void>;
|
|
37
64
|
//#endregion
|
|
38
|
-
export { FastMCPServerOptions, OAuthConfig, createFastMCPServer, startServer };
|
|
65
|
+
export { FastMCPServerOptions, OAuthConfig, StartServerOptions, createFastMCPServer, startServer };
|
|
39
66
|
//# sourceMappingURL=server.d.ts.map
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{loggers as e}from"./utils/logger.js";import{detachUserSchema as t,executeSchema as n,getUserStatsSchema as r,isAttachedSchema as i,listUsersSchema as a,querySchema as o,resolveUserId as s}from"./tools/index.js";import{DuckPondServer as c}from"./server-core.js";import{startUIServer as l}from"./ui-server.js";import{createHash as u,randomBytes as d,webcrypto as f}from"crypto";import{createRequire as p}from"module";import{FastMCP as m}from"fastmcp";import*as h from"jsonwebtoken";import{URL as g}from"url";globalThis.crypto||(globalThis.crypto=f);const _=p(import.meta.url)(`../package.json`),v=e.fastmcp,y=process.env.DUCKPOND_JWT_SECRET||d(32).toString(`hex`),b=process.env.DUCKPOND_JWT_EXPIRES_IN?parseInt(process.env.DUCKPOND_JWT_EXPIRES_IN,10):365*24*60*60,x=new Map,S=new Map;function C(e){v(`🚀 Initializing FastMCP server...`);let l=new c(e.config),u={name:`duckpond`,version:_.version,health:{enabled:!0,path:`/health`,status:200,message:JSON.stringify({status:`healthy`,service:`duckpond-mcp-server`,version:_.version,timestamp:new Date().toISOString()})}},d=e.oauth?.enabled||e.basicAuth?new m({...u,oauth:{enabled:!0,authorizationServer:{issuer:e.oauth?.issuer||`http://localhost:${e.port||3e3}`,authorizationEndpoint:`${e.oauth?.issuer||`http://localhost:${e.port||3e3}`}/oauth/authorize`,tokenEndpoint:`${e.oauth?.issuer||`http://localhost:${e.port||3e3}`}/oauth/token`,jwksUri:`${e.oauth?.issuer||`http://localhost:${e.port||3e3}`}/oauth/jwks`,registrationEndpoint:`${e.oauth?.issuer||`http://localhost:${e.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||e.oauth?.resource||`${e.oauth?.issuer||`http://localhost:${e.port||3e3}`}/mcp`,authorizationServers:[e.oauth?.issuer||`http://localhost:${e.port||3e3}`]}},authenticate:t=>{let n=t.headers?.authorization,r=e.oauth?.issuer||`http://localhost:${e.port||3e3}`;if(!n)throw e.oauth?.enabled?new Response(JSON.stringify({error:`unauthorized`,error_description:`Authorization required. Please authenticate via OAuth.`}),{status:401,statusText:`Unauthorized`,headers:{"Content-Type":`application/json`,"WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${r}/oauth/authorize", resource="${r}/.well-known/oauth-protected-resource"`}}):new Response(JSON.stringify({error:`unauthorized`,error_description:`Authorization required.`}),{status:401,statusText:`Unauthorized`,headers:{"Content-Type":`application/json`}});if(e.basicAuth&&n.startsWith(`Basic `)){let[t,r]=Buffer.from(n.slice(6),`base64`).toString(`utf-8`).split(`:`);if(t===e.basicAuth.username&&r===e.basicAuth.password)return Promise.resolve({userId:e.basicAuth.userId||t,email:e.basicAuth.email||`${t}@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(e.oauth?.enabled&&n.startsWith(`Bearer `)){let t=n.slice(7);try{let n=h.verify(t,y);if(!n.sub||!n.iat||!n.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 i=e.oauth?.resource||`${r}/mcp`;if(n.aud&&n.aud!==i)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:n.sub,email:n.email||``,scope:n.scope||`read write`})}catch(e){throw e instanceof Response?e:new Response(JSON.stringify({error:`invalid_token`,error_description:`Invalid or expired token`}),{status:401,statusText:`Unauthorized`,headers:{"Content-Type":`application/json`,"WWW-Authenticate":`Bearer realm="MCP", error="invalid_token", error_description="Invalid or expired token"`}})}}throw new Response(JSON.stringify({error:`unauthorized`,error_description:`Invalid authorization header format`}),{status:401,statusText:`Unauthorized`,headers:{"Content-Type":`application/json`,"WWW-Authenticate":`Bearer realm="MCP", authorization_uri="${r}/oauth/authorize", resource="${r}/.well-known/oauth-protected-resource"`}})}}):new m(u),f=(e,t)=>{if(typeof t==`bigint`)return Number.isSafeInteger(Number(t))?Number(t):t.toString();if(t&&typeof t==`object`&&`micros`in t){let e=t.micros,n=typeof e==`bigint`?Number(e/1000n):Number(e)/1e3;return new Date(n).toISOString()}return t};d.addTool({name:`query`,description:`Execute a SQL query for a specific user and return results`,parameters:o,execute:async e=>{try{let t=s(e.userId),n=await l.query(t,e.sql);return n.success?JSON.stringify({rows:n.data,rowCount:n.data.length,executionTime:n.executionTime},f,2):`ERROR: ${n.error.message}`}catch(e){v(`Error in query tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),d.addTool({name:`execute`,description:`Execute SQL statement (DDL/DML) for a specific user without returning results`,parameters:n,execute:async e=>{try{let t=s(e.userId),n=await l.execute(t,e.sql);return n.success?JSON.stringify({success:!0,message:`Statement executed successfully`,executionTime:n.executionTime},null,2):`ERROR: ${n.error.message}`}catch(e){v(`Error in execute tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),d.addTool({name:`getUserStats`,description:`Get statistics about a user's database (memory usage, query count, etc.)`,parameters:r,execute:async e=>{try{let t=s(e.userId),n=await l.getUserStats(t);return n.success?JSON.stringify({...n.data,lastAccess:n.data.lastAccess.toISOString()},null,2):`ERROR: ${n.error.message}`}catch(e){v(`Error in getUserStats tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),d.addTool({name:`isAttached`,description:`Check if a user's database is currently cached in memory`,parameters:i,execute:async e=>{try{let t=s(e.userId),n=l.isAttached(t);return n.success?JSON.stringify({attached:n.data,userId:t},null,2):`ERROR: ${n.error.message}`}catch(e){v(`Error in isAttached tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),d.addTool({name:`detachUser`,description:`Manually detach a user's database from the cache to free resources`,parameters:t,execute:async e=>{try{let t=s(e.userId),n=await l.detachUser(t);return n.success?JSON.stringify({success:!0,message:`User ${t} detached successfully`},null,2):`ERROR: ${n.error.message}`}catch(e){v(`Error in detachUser tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),d.addTool({name:`listUsers`,description:`List all currently cached users and cache statistics`,parameters:a,execute:async()=>{try{let e=l.listUsers();return e.success?JSON.stringify(e.data,null,2):`ERROR: ${e.error.message}`}catch(e){v(`Error in listUsers tool:`,e);let t=e instanceof Error?e.message:String(e);return`ERROR: ${JSON.stringify({error:t},null,2)}`}}}),e.oauth?.enabled&&w(d,e);let p=d.getApp();return p.get(`/`,t=>{let n=e.oauth?.issuer||`http://localhost:${e.port||3e3}`,r={name:`DuckPond MCP Server`,version:_.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:e.oauth?.enabled||!1,basicAuth:!!e.basicAuth}},endpoints:{mcp:`${n}${e.endpoint||`/mcp`}`,health:`${n}/health`,ui:`${n}/ui/:userId`,...e.oauth?.enabled&&{oauth:{authorization:`${n}/oauth/authorize`,token:`${n}/oauth/token`,jwks:`${n}/oauth/jwks`,register:`${n}/oauth/register`}}},timestamp:new Date().toISOString()};return t.json(r)}),T(p,l,e),v(`✓ FastMCP server created`),{server:d,duckpond:l}}function w(e,t){let n=e.getApp();setInterval(()=>{let e=Date.now();for(let[t,n]of x.entries())e-n.createdAt>6e5&&x.delete(t);for(let[t,n]of S.entries())e-n.createdAt>2592e6&&S.delete(t)},6e4),n.get(`/oauth/authorize`,e=>{let t=e.req.query(),n=t.response_type,r=t.redirect_uri,i=t.state,a=t.code_challenge,o=t.code_challenge_method,s=t.client_id;if(n!==`code`)return e.json({error:`unsupported_response_type`,error_description:`Only 'code' response type is supported`},400);if(!r)return e.json({error:`invalid_request`,error_description:`redirect_uri is required`},400);if(a&&(!o||![`S256`,`plain`].includes(o)))return e.json({error:`invalid_request`,error_description:`Invalid code_challenge_method. Only 'S256' and 'plain' are supported`},400);let c=`
|
|
2
2
|
<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
@@ -44,5 +44,5 @@ import{n as e}from"./logger-CX5FKgvo.js";import{detachUserSchema as t,executeSch
|
|
|
44
44
|
</html>`;return e.html(c)}),n.post(`/oauth/authorize`,async e=>{try{let n=await e.req.text(),r=new URLSearchParams(n),i=r.get(`username`),a=r.get(`password`),o=r.get(`redirect_uri`),s=r.get(`state`),c=r.get(`code_challenge`),l=r.get(`code_challenge_method`);if(i!==t.oauth?.username||a!==t.oauth?.password)return e.html(`
|
|
45
45
|
<!DOCTYPE html>
|
|
46
46
|
<html><head><title>Login Failed</title><style>body{font-family:Arial;max-width:400px;margin:100px auto;padding:20px;}.error{color:red;background:#fee;padding:10px;border-radius:4px;margin-bottom:15px;}</style></head>
|
|
47
|
-
<body><div class="error">❌ Invalid username or password</div><a href="javascript:history.back()">← Try Again</a></body></html>`,401);let u=d(16).toString(`hex`);x.set(u,{createdAt:Date.now(),redirectUri:o||``,codeChallenge:c||void 0,codeChallengeMethod:l||void 0,userId:t.oauth?.userId||i||`oauth-user`});let f=new g(o||``);return f.searchParams.set(`code`,u),s&&f.searchParams.set(`state`,s),e.redirect(f.toString(),302)}catch{return e.json({error:`invalid_request`,error_description:`Failed to process authorization request`},400)}}),n.post(`/oauth/token`,async e=>{let n=await e.req.text(),r=new URLSearchParams(n),i=r.get(`grant_type`),a=r.get(`code`),o=r.get(`redirect_uri`),s=r.get(`code_verifier`),c=r.get(`refresh_token`);if(i===`refresh_token`){if(!c)return e.json({error:`invalid_request`,error_description:`refresh_token is required for refresh_token grant type`},400);let n=S.get(c);if(!n)return e.json({error:`invalid_grant`,error_description:`Invalid or expired refresh token`},400);S.delete(c);let r={sub:n.userId,email:n.email||``,scope:`read write`,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,aud:t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`},i=d(32).toString(`hex`);S.set(i,{createdAt:Date.now(),userId:n.userId,email:n.email});let a=h.sign(r,y);return e.json({access_token:a,token_type:`Bearer`,expires_in:b,scope:`read write`,refresh_token:i})}if(i!==`authorization_code`)return e.json({error:`unsupported_grant_type`,error_description:`Only 'authorization_code' and 'refresh_token' grant types are supported`},400);let l=x.get(a||``);if(!l)return e.json({error:`invalid_grant`,error_description:`Invalid or expired authorization code`},400);if(l.redirectUri&&l.redirectUri!==o)return e.json({error:`invalid_grant`,error_description:`redirect_uri mismatch`},400);if(l.codeChallenge){if(!s)return e.json({error:`invalid_grant`,error_description:`code_verifier is required when code_challenge was used`},400);let t;if(t=l.codeChallengeMethod===`S256`?u(`sha256`).update(s).digest().toString(`base64url`):s,t!==l.codeChallenge)return e.json({error:`invalid_grant`,error_description:`Invalid code_verifier`},400)}x.delete(a);let f={sub:l.userId,email:t.oauth?.email||``,scope:`read write`,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,aud:t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`},p=d(32).toString(`hex`);S.set(p,{createdAt:Date.now(),userId:l.userId,email:t.oauth?.email});let m=h.sign(f,y);return e.json({access_token:m,token_type:`Bearer`,expires_in:b,scope:`read write`,refresh_token:p})}),n.get(`/oauth/jwks`,e=>e.json({keys:[{kty:`oct`,use:`sig`,kid:`duckpond-hmac-key`,alg:`HS256`}]})),n.post(`/oauth/register`,async e=>{try{let t={};try{let n=await e.req.text();if(n&&n!==`[object Object]`)try{t=JSON.parse(n)}catch{t=Object.fromEntries(new URLSearchParams(n))}}catch(e){v(`Error parsing request body:`,e)}let n={client_id:`client-${d(8).toString(`hex`)}`,client_secret:d(16).toString(`hex`),client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:t.grant_types||[`authorization_code`],response_types:t.response_types||[`code`],redirect_uris:t.redirect_uris||[],token_endpoint_auth_method:t.token_endpoint_auth_method||`client_secret_post`};return t.client_name&&(n.client_name=t.client_name),t.scope&&(n.scope=t.scope),e.json(n,201)}catch(t){return e.json({error:`invalid_client_metadata`,error_description:`Invalid client registration request: `+(t instanceof Error?t.message:String(t))},400)}}),v(`✓ OAuth flow endpoints added`)}function T(e,t,n){let r=n.oauth?.issuer||`http://localhost:${n.port||3e3}`,i=t.getUIPort();e.get(`/ui`,e=>{let n=t.getCurrentUIUser(),a=t.listUsers();return e.json({message:n?`UI active for user: ${n}. Access directly at http://localhost:${i}`:`No UI active. Visit /ui/:userId to start DuckDB UI for a user.`,currentUser:n,uiUrl:n?`http://localhost:${i}`:null,availableUsers:a.success?a.data.users:[],endpoints:{startUI:`${r}/ui/:userId`}})}),e.get(`/ui/:userId`,async e=>{let n=e.req.param(`userId`);v(`Starting UI for user: ${n}`);let r=await t.startUI(n);return r.success?e.json({success:!0,message:`UI started for user: ${n}`,uiUrl:`http://localhost:${i}`,hint:`Access the DuckDB UI directly at the uiUrl above`}):e.json({error:`Failed to start UI`,message:r.error.message,details:r.error.details},500)}),v(`✓ UI endpoints added`)}async function E(e,t){let{server:
|
|
47
|
+
<body><div class="error">❌ Invalid username or password</div><a href="javascript:history.back()">← Try Again</a></body></html>`,401);let u=d(16).toString(`hex`);x.set(u,{createdAt:Date.now(),redirectUri:o||``,codeChallenge:c||void 0,codeChallengeMethod:l||void 0,userId:t.oauth?.userId||i||`oauth-user`});let f=new g(o||``);return f.searchParams.set(`code`,u),s&&f.searchParams.set(`state`,s),e.redirect(f.toString(),302)}catch{return e.json({error:`invalid_request`,error_description:`Failed to process authorization request`},400)}}),n.post(`/oauth/token`,async e=>{let n=await e.req.text(),r=new URLSearchParams(n),i=r.get(`grant_type`),a=r.get(`code`),o=r.get(`redirect_uri`),s=r.get(`code_verifier`),c=r.get(`refresh_token`);if(i===`refresh_token`){if(!c)return e.json({error:`invalid_request`,error_description:`refresh_token is required for refresh_token grant type`},400);let n=S.get(c);if(!n)return e.json({error:`invalid_grant`,error_description:`Invalid or expired refresh token`},400);S.delete(c);let r={sub:n.userId,email:n.email||``,scope:`read write`,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,aud:t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`},i=d(32).toString(`hex`);S.set(i,{createdAt:Date.now(),userId:n.userId,email:n.email});let a=h.sign(r,y);return e.json({access_token:a,token_type:`Bearer`,expires_in:b,scope:`read write`,refresh_token:i})}if(i!==`authorization_code`)return e.json({error:`unsupported_grant_type`,error_description:`Only 'authorization_code' and 'refresh_token' grant types are supported`},400);let l=x.get(a||``);if(!l)return e.json({error:`invalid_grant`,error_description:`Invalid or expired authorization code`},400);if(l.redirectUri&&l.redirectUri!==o)return e.json({error:`invalid_grant`,error_description:`redirect_uri mismatch`},400);if(l.codeChallenge){if(!s)return e.json({error:`invalid_grant`,error_description:`code_verifier is required when code_challenge was used`},400);let t;if(t=l.codeChallengeMethod===`S256`?u(`sha256`).update(s).digest().toString(`base64url`):s,t!==l.codeChallenge)return e.json({error:`invalid_grant`,error_description:`Invalid code_verifier`},400)}x.delete(a);let f={sub:l.userId,email:t.oauth?.email||``,scope:`read write`,iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+b,iss:t.oauth?.issuer||`http://localhost:${t.port||3e3}`,aud:t.oauth?.resource||`${t.oauth?.issuer||`http://localhost:${t.port||3e3}`}/mcp`},p=d(32).toString(`hex`);S.set(p,{createdAt:Date.now(),userId:l.userId,email:t.oauth?.email});let m=h.sign(f,y);return e.json({access_token:m,token_type:`Bearer`,expires_in:b,scope:`read write`,refresh_token:p})}),n.get(`/oauth/jwks`,e=>e.json({keys:[{kty:`oct`,use:`sig`,kid:`duckpond-hmac-key`,alg:`HS256`}]})),n.post(`/oauth/register`,async e=>{try{let t={};try{let n=await e.req.text();if(n&&n!==`[object Object]`)try{t=JSON.parse(n)}catch{t=Object.fromEntries(new URLSearchParams(n))}}catch(e){v(`Error parsing request body:`,e)}let n={client_id:`client-${d(8).toString(`hex`)}`,client_secret:d(16).toString(`hex`),client_id_issued_at:Math.floor(Date.now()/1e3),client_secret_expires_at:0,grant_types:t.grant_types||[`authorization_code`],response_types:t.response_types||[`code`],redirect_uris:t.redirect_uris||[],token_endpoint_auth_method:t.token_endpoint_auth_method||`client_secret_post`};return t.client_name&&(n.client_name=t.client_name),t.scope&&(n.scope=t.scope),e.json(n,201)}catch(t){return e.json({error:`invalid_client_metadata`,error_description:`Invalid client registration request: `+(t instanceof Error?t.message:String(t))},400)}}),v(`✓ OAuth flow endpoints added`)}function T(e,t,n){let r=n.oauth?.issuer||`http://localhost:${n.port||3e3}`,i=t.getUIPort();e.get(`/ui`,e=>{let n=t.getCurrentUIUser(),a=t.listUsers();return e.json({message:n?`UI active for user: ${n}. Access directly at http://localhost:${i}`:`No UI active. Visit /ui/:userId to start DuckDB UI for a user.`,currentUser:n,uiUrl:n?`http://localhost:${i}`:null,availableUsers:a.success?a.data.users:[],endpoints:{startUI:`${r}/ui/:userId`}})}),e.get(`/ui/:userId`,async e=>{let n=e.req.param(`userId`);v(`Starting UI for user: ${n}`);let r=await t.startUI(n);return r.success?e.json({success:!0,message:`UI started for user: ${n}`,uiUrl:`http://localhost:${i}`,hint:`Access the DuckDB UI directly at the uiUrl above`}):e.json({error:`Failed to start UI`,message:r.error.message,details:r.error.details},500)}),v(`✓ UI endpoints added`)}async function E(e,t){let n=`options`in e&&`transport`in e,r=n?e.options:e,i=n?e.transport:t,a=n?e.beforeStart:void 0,{server:o,duckpond:s}=C(r),c=await s.init();if(!c.success)throw Error(`Failed to initialize DuckPond: ${c.error.message}`);if(v(`DuckPond initialized successfully`),a&&await a({server:o,duckpond:s}),r.ui?.internalPort&&s.setUIPort(r.ui.internalPort),i===`stdio`){if(await o.start({transportType:`stdio`}),v(`✓ FastMCP server running with stdio transport`),r.ui?.enabled)if(r.ui.autoStartUser){v(`Auto-starting UI for user: ${r.ui.autoStartUser}`);let e=await s.startUI(r.ui.autoStartUser);e.success?console.error(`🖥️ DuckDB UI running at http://localhost:${s.getUIPort()}`):v(`Failed to auto-start UI: ${e.error.message}`)}else await l({port:r.ui.port,duckpond:s})}else await o.start({transportType:`httpStream`,httpStream:{port:r.port||3e3,endpoint:r.endpoint||`/mcp`}}),v(`✓ FastMCP server running on http://0.0.0.0:${r.port||3e3}${r.endpoint||`/mcp`}`),v(`🔌 Connect with StreamableHTTPClientTransport`);process.on(`SIGINT`,async()=>{v(`Received SIGINT, closing server...`),await s.close(),process.exit(0)}),process.on(`SIGTERM`,async()=>{v(`Received SIGTERM, closing server...`),await s.close(),process.exit(0)})}export{C as createFastMCPServer,E as startServer};
|
|
48
48
|
//# sourceMappingURL=server.js.map
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["accessTokenPayload","accessToken","expectedChallenge: string","registrationRequest: OAuthClientRegistrationRequest","response: OAuthClientRegistrationResponse"],"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 autoStartUser?: 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 // DuckDB type-safe JSON serializer (handles BigInt and timestamp objects)\n const duckDBReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === \"bigint\") {\n // Convert to number if safe, otherwise string\n return Number.isSafeInteger(Number(value)) ? Number(value) : value.toString()\n }\n // Handle DuckDB timestamp objects {micros: bigint}\n if (value && typeof value === \"object\" && \"micros\" in value) {\n const micros = (value as { micros: bigint }).micros\n const ms = typeof micros === \"bigint\" ? Number(micros / 1000n) : Number(micros) / 1000\n return new Date(ms).toISOString()\n }\n return value\n }\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 duckDBReplacer,\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\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n const listResult = duckpond.listUsers()\n return c.json({\n message: currentUser\n ? `UI active for user: ${currentUser}. Access directly at http://localhost:${uiInternalPort}`\n : \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser,\n uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `${baseUrl}/ui/:userId`,\n },\n })\n })\n\n // GET /ui/:userId - Start UI for a specific user\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 return c.json({\n success: true,\n message: `UI started for user: ${userId}`,\n uiUrl: `http://localhost:${uiInternalPort}`,\n hint: \"Access the DuckDB UI directly at the uiUrl above\",\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 if enabled in stdio mode\n if (options.ui?.enabled) {\n if (options.ui.autoStartUser) {\n // Auto-start UI directly for default user (no management server needed)\n log(`Auto-starting UI for user: ${options.ui.autoStartUser}`)\n const uiResult = await duckpond.startUI(options.ui.autoStartUser)\n if (uiResult.success) {\n console.error(`🖥️ DuckDB UI running at http://localhost:${duckpond.getUIPort()}`)\n } else {\n log(`Failed to auto-start UI: ${uiResult.error.message}`)\n }\n } else {\n // No default user - start management server for manual user selection\n await startUIServer({\n port: options.ui.port,\n duckpond,\n })\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":"ogBAGK,WAAW,SACd,WAAW,OAAS,GAQtB,MAAM,EADU,EAAc,OAAO,KAAK,IAAI,CAClB,kBAAkB,CAmBxC,EAAM,EAAQ,QAgCd,EAAa,QAAQ,IAAI,qBAAuB,EAAY,GAAG,CAAC,SAAS,MAAM,CAG/E,EAAiB,QAAQ,IAAI,wBAC/B,SAAS,QAAQ,IAAI,wBAAyB,GAAG,CACjD,IAAM,GAAK,GAAK,GAGd,EAAqB,IAAI,IAWzB,EAAgB,IAAI,IAuC1B,SAAgB,EAAoB,EAGlC,CACA,EAAI,oCAAoC,CAGxC,IAAM,EAAW,IAAI,EAAe,EAAQ,OAAO,CAG7C,EAAa,CACjB,KAAM,WACN,QAAS,EAAY,QACrB,OAAQ,CACN,QAAS,GACT,KAAM,UACN,OAAQ,IACR,QAAS,KAAK,UAAU,CACtB,OAAQ,UACR,QAAS,sBACT,QAAS,EAAY,QACrB,UAAW,IAAI,MAAM,CAAC,aAAa,CACpC,CAAC,CACH,CACF,CAGK,EACJ,EAAQ,OAAO,SAAW,EAAQ,UAC9B,IAAI,EAAqB,CACvB,GAAG,EACH,MAAO,CACL,QAAS,GACT,oBAAqB,CACnB,OAAQ,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,MAAQ,MACrE,sBAAuB,GAAG,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,MA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D,CAItD,QAAQ,GAAG,SAAU,SAAY,CAC/B,EAAI,qCAAqC,CACzC,MAAM,EAAS,OAAO,CACtB,QAAQ,KAAK,EAAE,EACf,CAEF,QAAQ,GAAG,UAAW,SAAY,CAChC,EAAI,sCAAsC,CAC1C,MAAM,EAAS,OAAO,CACtB,QAAQ,KAAK,EAAE,EACf"}
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"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 { createHash, randomBytes } from \"crypto\"\nimport { FastMCP } from \"fastmcp\"\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 autoStartUser?: 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 // DuckDB type-safe JSON serializer (handles BigInt and timestamp objects)\n const duckDBReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === \"bigint\") {\n // Convert to number if safe, otherwise string\n return Number.isSafeInteger(Number(value)) ? Number(value) : value.toString()\n }\n // Handle DuckDB timestamp objects {micros: bigint}\n if (value && typeof value === \"object\" && \"micros\" in value) {\n const micros = (value as { micros: bigint }).micros\n const ms = typeof micros === \"bigint\" ? Number(micros / 1000n) : Number(micros) / 1000\n return new Date(ms).toISOString()\n }\n return value\n }\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 duckDBReplacer,\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\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n const listResult = duckpond.listUsers()\n return c.json({\n message: currentUser\n ? `UI active for user: ${currentUser}. Access directly at http://localhost:${uiInternalPort}`\n : \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser,\n uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n availableUsers: listResult.success ? listResult.data.users : [],\n endpoints: {\n startUI: `${baseUrl}/ui/:userId`,\n },\n })\n })\n\n // GET /ui/:userId - Start UI for a specific user\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 return c.json({\n success: true,\n message: `UI started for user: ${userId}`,\n uiUrl: `http://localhost:${uiInternalPort}`,\n hint: \"Access the DuckDB UI directly at the uiUrl above\",\n })\n })\n\n log(\"✓ UI endpoints added\")\n}\n\nexport type StartServerOptions = {\n options: FastMCPServerOptions\n transport: \"stdio\" | \"http\"\n /** Hook called after DuckPond init but before server start - use to register custom tools */\n beforeStart?: (ctx: { server: FastMCP; duckpond: DuckPondServer }) => void | Promise<void>\n}\n\n/**\n * Start the DuckPond MCP server with full configuration\n *\n * @example\n * ```typescript\n * import { startServer, getDefaultUserId } from \"duckpond-mcp-server/lib\"\n *\n * await startServer({\n * options: { config: { dataDir: \"~/data\" }, ui: { enabled: true, port: 4000, autoStartUser: \"claude\" } },\n * transport: \"stdio\",\n * beforeStart: async ({ server, duckpond }) => {\n * // Register custom tools before server starts\n * server.addTool({ name: \"my_tool\", ... })\n * }\n * })\n * ```\n */\nexport async function startServer(opts: StartServerOptions): Promise<void>\n/** @deprecated Use object form: startServer({ options, transport, beforeStart }) */\nexport async function startServer(options: FastMCPServerOptions, transport: \"stdio\" | \"http\"): Promise<void>\nexport async function startServer(\n optsOrOptions: StartServerOptions | FastMCPServerOptions,\n transportArg?: \"stdio\" | \"http\",\n): Promise<void> {\n // Handle both old and new signatures\n const isNewSignature = \"options\" in optsOrOptions && \"transport\" in optsOrOptions\n const options = isNewSignature ? optsOrOptions.options : optsOrOptions\n const transport = isNewSignature ? optsOrOptions.transport : transportArg!\n const beforeStart = isNewSignature ? optsOrOptions.beforeStart : undefined\n\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 // Call beforeStart hook if provided (allows registering custom tools)\n if (beforeStart) {\n await beforeStart({ server, duckpond })\n }\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 if enabled in stdio mode\n if (options.ui?.enabled) {\n if (options.ui.autoStartUser) {\n // Auto-start UI directly for default user (no management server needed)\n log(`Auto-starting UI for user: ${options.ui.autoStartUser}`)\n const uiResult = await duckpond.startUI(options.ui.autoStartUser)\n if (uiResult.success) {\n console.error(`🖥️ DuckDB UI running at http://localhost:${duckpond.getUIPort()}`)\n } else {\n log(`Failed to auto-start UI: ${uiResult.error.message}`)\n }\n } else {\n // No default user - start management server for manual user selection\n await startUIServer({\n port: options.ui.port,\n duckpond,\n })\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":"igBAGK,WAAW,SACd,WAAW,OAAS,GAQtB,MAAM,EADU,EAAc,OAAO,KAAK,IAAI,CAClB,kBAAkB,CAmBxC,EAAM,EAAQ,QAgCd,EAAa,QAAQ,IAAI,qBAAuB,EAAY,GAAG,CAAC,SAAS,MAAM,CAG/E,EAAiB,QAAQ,IAAI,wBAC/B,SAAS,QAAQ,IAAI,wBAAyB,GAAG,CACjD,IAAM,GAAK,GAAK,GAGd,EAAqB,IAAI,IAWzB,EAAgB,IAAI,IAuC1B,SAAgB,EAAoB,EAGlC,CACA,EAAI,oCAAoC,CAGxC,IAAM,EAAW,IAAI,EAAe,EAAQ,OAAO,CAG7C,EAAa,CACjB,KAAM,WACN,QAAS,EAAY,QACrB,OAAQ,CACN,QAAS,GACT,KAAM,UACN,OAAQ,IACR,QAAS,KAAK,UAAU,CACtB,OAAQ,UACR,QAAS,sBACT,QAAS,EAAY,QACrB,UAAW,IAAI,MAAM,CAAC,aAAa,CACpC,CAAC,CACH,CACF,CAGK,EACJ,EAAQ,OAAO,SAAW,EAAQ,UAC9B,IAAI,EAAqB,CACvB,GAAG,EACH,MAAO,CACL,QAAS,GACT,oBAAqB,CACnB,OAAQ,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,MAAQ,MACrE,sBAAuB,GAAG,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,MAAQ,MAAO,kBAC9F,cAAe,GAAG,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,MAAQ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,UAAY,OAChC,CACF,CAAC,CACF,EAAI,8CAA8C,EAAQ,MAAQ,MAAO,EAAQ,UAAY,SAAS,CACtG,EAAI,gDAAgD,CAItD,QAAQ,GAAG,SAAU,SAAY,CAC/B,EAAI,qCAAqC,CACzC,MAAM,EAAS,OAAO,CACtB,QAAQ,KAAK,EAAE,EACf,CAEF,QAAQ,GAAG,UAAW,SAAY,CAChC,EAAI,sCAAsC,CAC1C,MAAM,EAAS,OAAO,CACtB,QAAQ,KAAK,EAAE,EACf"}
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -2,7 +2,6 @@ import { DuckPondServer } from "../server-core.js";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
|
|
4
4
|
//#region src/tools/index.d.ts
|
|
5
|
-
|
|
6
5
|
/**
|
|
7
6
|
* Get the default user ID from environment variable
|
|
8
7
|
*/
|
|
@@ -18,60 +17,36 @@ declare function resolveUserId(inputUserId?: string): string;
|
|
|
18
17
|
declare const querySchema: z.ZodObject<{
|
|
19
18
|
userId: z.ZodOptional<z.ZodString>;
|
|
20
19
|
sql: z.ZodString;
|
|
21
|
-
},
|
|
22
|
-
sql: string;
|
|
23
|
-
userId?: string | undefined;
|
|
24
|
-
}, {
|
|
25
|
-
sql: string;
|
|
26
|
-
userId?: string | undefined;
|
|
27
|
-
}>;
|
|
20
|
+
}, z.core.$strip>;
|
|
28
21
|
/**
|
|
29
22
|
* Zod schema for execute tool
|
|
30
23
|
*/
|
|
31
24
|
declare const executeSchema: z.ZodObject<{
|
|
32
25
|
userId: z.ZodOptional<z.ZodString>;
|
|
33
26
|
sql: z.ZodString;
|
|
34
|
-
},
|
|
35
|
-
sql: string;
|
|
36
|
-
userId?: string | undefined;
|
|
37
|
-
}, {
|
|
38
|
-
sql: string;
|
|
39
|
-
userId?: string | undefined;
|
|
40
|
-
}>;
|
|
27
|
+
}, z.core.$strip>;
|
|
41
28
|
/**
|
|
42
29
|
* Zod schema for getUserStats tool
|
|
43
30
|
*/
|
|
44
31
|
declare const getUserStatsSchema: z.ZodObject<{
|
|
45
32
|
userId: z.ZodOptional<z.ZodString>;
|
|
46
|
-
},
|
|
47
|
-
userId?: string | undefined;
|
|
48
|
-
}, {
|
|
49
|
-
userId?: string | undefined;
|
|
50
|
-
}>;
|
|
33
|
+
}, z.core.$strip>;
|
|
51
34
|
/**
|
|
52
35
|
* Zod schema for isAttached tool
|
|
53
36
|
*/
|
|
54
37
|
declare const isAttachedSchema: z.ZodObject<{
|
|
55
38
|
userId: z.ZodOptional<z.ZodString>;
|
|
56
|
-
},
|
|
57
|
-
userId?: string | undefined;
|
|
58
|
-
}, {
|
|
59
|
-
userId?: string | undefined;
|
|
60
|
-
}>;
|
|
39
|
+
}, z.core.$strip>;
|
|
61
40
|
/**
|
|
62
41
|
* Zod schema for detachUser tool
|
|
63
42
|
*/
|
|
64
43
|
declare const detachUserSchema: z.ZodObject<{
|
|
65
44
|
userId: z.ZodOptional<z.ZodString>;
|
|
66
|
-
},
|
|
67
|
-
userId?: string | undefined;
|
|
68
|
-
}, {
|
|
69
|
-
userId?: string | undefined;
|
|
70
|
-
}>;
|
|
45
|
+
}, z.core.$strip>;
|
|
71
46
|
/**
|
|
72
47
|
* Zod schema for listUsers tool
|
|
73
48
|
*/
|
|
74
|
-
declare const listUsersSchema: z.ZodObject<{},
|
|
49
|
+
declare const listUsersSchema: z.ZodObject<{}, z.core.$strip>;
|
|
75
50
|
/**
|
|
76
51
|
* Tool implementations for MCP server
|
|
77
52
|
*/
|
package/dist/tools/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{loggers as e}from"../utils/logger.js";import{z as t}from"zod";const n=e.tools;function r(){return process.env.DUCKPOND_DEFAULT_USER}function i(e){let t=e||r();if(!t)throw Error(`userId is required. Either provide it in the request or set DUCKPOND_DEFAULT_USER environment variable.`);return t}const a=t.object({userId:t.string().min(1).optional().describe(`User identifier (optional if DUCKPOND_DEFAULT_USER is set)`),sql:t.string().min(1).describe(`SQL query to execute`)}),o=t.object({userId:t.string().min(1).optional().describe(`User identifier (optional if DUCKPOND_DEFAULT_USER is set)`),sql:t.string().min(1).describe(`SQL statement to execute (DDL/DML)`)}),s=t.object({userId:t.string().min(1).optional().describe(`User identifier (optional if DUCKPOND_DEFAULT_USER is set)`)}),c=t.object({userId:t.string().min(1).optional().describe(`User identifier (optional if DUCKPOND_DEFAULT_USER is set)`)}),l=t.object({userId:t.string().min(1).optional().describe(`User identifier (optional if DUCKPOND_DEFAULT_USER is set)`)}),u=t.object({}),d={async query(e,t){let r=i(t.userId);n(`Tool: query for user ${r}`);let a=await e.query(r,t.sql);if(!a.success)throw Error(a.error.message);return{content:[{type:`text`,text:JSON.stringify({rows:a.data,rowCount:a.data.length,executionTime:a.executionTime},null,2)}]}},async execute(e,t){let r=i(t.userId);n(`Tool: execute for user ${r}`);let a=await e.execute(r,t.sql);if(!a.success)throw Error(a.error.message);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Statement executed successfully`,executionTime:a.executionTime},null,2)}]}},async getUserStats(e,t){let r=i(t.userId);n(`Tool: getUserStats for user ${r}`);let a=await e.getUserStats(r);if(!a.success)throw Error(a.error.message);return{content:[{type:`text`,text:JSON.stringify({...a.data,lastAccess:a.data.lastAccess.toISOString()},null,2)}]}},isAttached(e,t){let r=i(t.userId);n(`Tool: isAttached for user ${r}`);let a=e.isAttached(r);if(!a.success)throw Error(a.error.message);return{content:[{type:`text`,text:JSON.stringify({attached:a.data,userId:r},null,2)}]}},async detachUser(e,t){let r=i(t.userId);n(`Tool: detachUser for user ${r}`);let a=await e.detachUser(r);if(!a.success)throw Error(a.error.message);return{content:[{type:`text`,text:JSON.stringify({success:!0,message:`User ${r} detached successfully`},null,2)}]}},listUsers(e,t){n(`Tool: listUsers`);let r=e.listUsers();if(!r.success)throw Error(r.error.message);return{content:[{type:`text`,text:JSON.stringify(r.data,null,2)}]}}};export{l as detachUserSchema,o as executeSchema,r as getDefaultUserId,s as getUserStatsSchema,c as isAttachedSchema,u as listUsersSchema,a as querySchema,i as resolveUserId,d as tools};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/tools/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"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":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"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":"qEAKA,MAAM,EAAM,EAAQ,MAKpB,SAAgB,GAAuC,CACrD,OAAO,QAAQ,IAAI,sBAOrB,SAAgB,EAAc,EAA8B,CAC1D,IAAM,EAAS,GAAe,GAAkB,CAChD,GAAI,CAAC,EACH,MAAU,MACR,0GACD,CAEH,OAAO,EAMT,MAAa,EAAc,EAAE,OAAO,CAClC,OAAQ,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,UAAU,CAAC,SAAS,6DAA6D,CAC3G,IAAK,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,uB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S,CACP,CACE,KAAM,OACN,KAAM,KAAK,UAAU,EAAO,KAAM,KAAM,EAAE,CAC3C,CACF,CACF,EAEJ"}
|
package/dist/ui-server.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import"./logger
|
|
1
|
+
import{loggers as e}from"./utils/logger.js";import{serve as t}from"@hono/node-server";import{Hono as n}from"hono";const r=e.core;async function i(e){let{port:i,duckpond:a}=e,o=a.getUIPort(),s=new n;s.get(`/ui`,e=>{let t=a.getCurrentUIUser(),n=a.listUsers();return e.json({message:t?`UI active for user: ${t}. Access directly at http://localhost:${o}`:`No UI active. Visit /ui/:userId to start DuckDB UI for a user.`,currentUser:t,uiUrl:t?`http://localhost:${o}`:null,availableUsers:n.success?n.data.users:[]})}),s.get(`/ui/:userId`,async e=>{let t=e.req.param(`userId`);r(`[UI Server] Starting UI for user: ${t}`);let n=await a.startUI(t);return n.success?e.json({success:!0,message:`UI started for user: ${t}`,uiUrl:`http://localhost:${o}`,hint:`Access the DuckDB UI directly at the uiUrl above`}):e.json({error:`Failed to start UI`,message:n.error.message,details:n.error.details},500)}),s.get(`/`,e=>{let t=a.getCurrentUIUser();return e.json({name:`DuckPond UI Server`,description:`Lightweight HTTP server for DuckDB UI access in stdio mode`,currentUIUser:t,uiUrl:t?`http://localhost:${o}`:null,endpoints:{startUI:`http://localhost:${i}/ui/:userId`,status:`http://localhost:${i}/ui`}})}),t({fetch:s.fetch,port:i}),r(`✓ UI server running at http://localhost:${i}/ui`),r(` Visit http://localhost:${i}/ui/:userId to start DuckDB UI`),r(` Then access DuckDB UI directly at http://localhost:${o}`)}export{i as startUIServer};
|
|
2
|
+
//# sourceMappingURL=ui-server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ui-server.js","names":[],"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 starting 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\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n const listResult = duckpond.listUsers()\n return c.json({\n message: currentUser\n ? `UI active for user: ${currentUser}. Access directly at http://localhost:${uiInternalPort}`\n : \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser,\n uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n availableUsers: listResult.success ? listResult.data.users : [],\n })\n })\n\n // GET /ui/:userId - Start UI for a specific user\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 return c.json({\n success: true,\n message: `UI started for user: ${userId}`,\n uiUrl: `http://localhost:${uiInternalPort}`,\n hint: \"Access the DuckDB UI directly at the uiUrl above\",\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 uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n endpoints: {\n startUI: `http://localhost:${port}/ui/:userId`,\n status: `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 log(` Then access D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@@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"debug";const t={core:e(`duckpond-mcp:core`),stdio:e(`duckpond-mcp:stdio`),fastmcp:e(`duckpond-mcp:fastmcp`),tools:e(`duckpond-mcp:tools`),main:e(`duckpond-mcp:main`)};function n(t){return e(`duckpond-mcp:${t}`)}export{n as createLogger,t as loggers};
|
|
2
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","names":[],"sources":["../../src/utils/logger.ts"],"sourcesContent":["import debug from \"debug\"\n\n/**\n * Debug loggers for different modules\n */\nexport const loggers = {\n core: debug(\"duckpond-mcp:core\"),\n stdio: debug(\"duckpond-mcp:stdio\"),\n fastmcp: debug(\"duckpond-mcp:fastmcp\"),\n tools: debug(\"duckpond-mcp:tools\"),\n main: debug(\"duckpond-mcp:main\"),\n}\n\n/**\n * Create a custom logger\n */\nexport function createLogger(namespace: string) {\n return debug(`duckpond-mcp:${namespace}`)\n}\n"],"mappings":"qBAKA,MAAa,EAAU,CACrB,KAAM,EAAM,oBAAoB,CAChC,MAAO,EAAM,qBAAqB,CAClC,QAAS,EAAM,uBAAuB,CACtC,MAAO,EAAM,qBAAqB,CAClC,KAAM,EAAM,oBAAoB,CACjC,CAKD,SAAgB,EAAa,EAAmB,CAC9C,OAAO,EAAM,gBAAgB,IAAY"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "duckpond-mcp-server",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "MCP server for multi-tenant DuckDB management with R2/S3 storage",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -42,22 +42,22 @@
|
|
|
42
42
|
"prepublishOnly": "pnpm validate"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@hono/node-server": "^1.19.
|
|
46
|
-
"
|
|
45
|
+
"@hono/node-server": "^1.19.9",
|
|
46
|
+
"fastmcp": "3.32.0",
|
|
47
47
|
"@types/express": "^5.0.6",
|
|
48
48
|
"@types/jsonwebtoken": "^9.0.10",
|
|
49
|
-
"commander": "^14.0.
|
|
49
|
+
"commander": "^14.0.3",
|
|
50
50
|
"debug": "^4.4.3",
|
|
51
|
-
"duckpond": "^0.4.
|
|
51
|
+
"duckpond": "^0.4.1",
|
|
52
52
|
"express": "^5.2.1",
|
|
53
|
-
"hono": "^4.11.
|
|
53
|
+
"hono": "^4.11.9",
|
|
54
54
|
"jsonwebtoken": "^9.0.3",
|
|
55
|
-
"zod": "^3.
|
|
55
|
+
"zod": "^4.3.6"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@types/node": "~24.10.
|
|
59
|
-
"ts-builds": "^2.
|
|
60
|
-
"tsdown": "^0.
|
|
58
|
+
"@types/node": "~24.10.13",
|
|
59
|
+
"ts-builds": "^2.4.0",
|
|
60
|
+
"tsdown": "^0.20.3",
|
|
61
61
|
"tsx": "^4.21.0",
|
|
62
62
|
"typescript": "^5.9.3"
|
|
63
63
|
},
|
|
@@ -79,5 +79,5 @@
|
|
|
79
79
|
"dist"
|
|
80
80
|
],
|
|
81
81
|
"prettier": "ts-builds/prettier",
|
|
82
|
-
"packageManager": "pnpm@10.
|
|
82
|
+
"packageManager": "pnpm@10.29.3+sha512.498e1fb4cca5aa06c1dcf2611e6fafc50972ffe7189998c409e90de74566444298ffe43e6cd2acdc775ba1aa7cc5e092a8b7054c811ba8c5770f84693d33d2dc"
|
|
83
83
|
}
|
package/dist/logger-CX5FKgvo.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"debug";const t={core:e(`duckpond-mcp:core`),stdio:e(`duckpond-mcp:stdio`),fastmcp:e(`duckpond-mcp:fastmcp`),tools:e(`duckpond-mcp:tools`),main:e(`duckpond-mcp:main`)};function n(t){return e(`duckpond-mcp:${t}`)}export{t as n,n as t};
|
|
2
|
-
//# sourceMappingURL=logger-CX5FKgvo.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"logger-CX5FKgvo.js","names":[],"sources":["../src/utils/logger.ts"],"sourcesContent":["import debug from \"debug\"\n\n/**\n * Debug loggers for different modules\n */\nexport const loggers = {\n core: debug(\"duckpond-mcp:core\"),\n stdio: debug(\"duckpond-mcp:stdio\"),\n fastmcp: debug(\"duckpond-mcp:fastmcp\"),\n tools: debug(\"duckpond-mcp:tools\"),\n main: debug(\"duckpond-mcp:main\"),\n}\n\n/**\n * Create a custom logger\n */\nexport function createLogger(namespace: string) {\n return debug(`duckpond-mcp:${namespace}`)\n}\n"],"mappings":"qBAKA,MAAa,EAAU,CACrB,KAAM,EAAM,oBAAoB,CAChC,MAAO,EAAM,qBAAqB,CAClC,QAAS,EAAM,uBAAuB,CACtC,MAAO,EAAM,qBAAqB,CAClC,KAAM,EAAM,oBAAoB,CACjC,CAKD,SAAgB,EAAa,EAAmB,CAC9C,OAAO,EAAM,gBAAgB,IAAY"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./logger-CX5FKgvo.js";import{DuckPond as t}from"duckpond";function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(n(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||`default`);if(n(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function i(e){var t=r(e,`string`);return n(t)==`symbol`?t:t+``}function a(e,t,n){return(t=i(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const o=e.core;var s=class{constructor(e){this.config=e,a(this,`pond`,null),a(this,`initialized`,!1),a(this,`currentUIUserId`,null),a(this,`uiInternalPort`,4213),a(this,`uiKeepaliveTimer`,null),a(this,`UI_KEEPALIVE_INTERVAL`,3e4),o(`DuckPondServer created`)}async init(){if(this.initialized)return o(`Already initialized`),{success:!0,data:void 0};o(`Initializing DuckPond...`);let e=Date.now();this.pond=new t(this.config);let n=await this.pond.init();return this.handleEither(n,Date.now()-e)}async query(e,t){if(!this.pond)return this.notInitializedError();o(`Query for user ${e}: ${t.substring(0,100)}...`);let n=Date.now(),r=await this.pond.query(e,t);return this.handleEither(r,Date.now()-n)}async execute(e,t){if(!this.pond)return this.notInitializedError();o(`Execute for user ${e}: ${t.substring(0,100)}...`);let n=Date.now(),r=await this.pond.execute(e,t);return this.handleEither(r,Date.now()-n)}async getUserStats(e){if(!this.pond)return this.notInitializedError();o(`Getting stats for user ${e}`);let t=Date.now(),n=await this.pond.getUserStats(e);return this.handleEither(n,Date.now()-t)}isAttached(e){if(!this.pond)return this.notInitializedError();let t=this.pond.isAttached(e);return o(`User ${e} attached: ${t}`),{success:!0,data:t}}async detachUser(e){if(!this.pond)return this.notInitializedError();o(`Detaching user ${e}`);let t=Date.now(),n=await this.pond.detachUser(e);return this.handleEither(n,Date.now()-t)}listUsers(){if(!this.pond)return this.notInitializedError();o(`Listing cached users`);let e=this.pond.listUsers();return{success:!0,data:{users:e.users.toArray(),count:e.count,maxActiveUsers:e.maxActiveUsers,utilizationPercent:e.utilizationPercent}}}async close(){if(!this.pond)return{success:!0,data:void 0};o(`Closing DuckPond...`);let e=Date.now();this.currentUIUserId&&await this.stopUI();let t=await this.pond.close();return this.initialized=!1,this.pond=null,this.handleEither(t,Date.now()-e)}async startUI(e){if(!this.pond)return this.notInitializedError();o(`Starting UI for user ${e}`);let t=Date.now();if(this.currentUIUserId&&this.currentUIUserId!==e&&(o(`Stopping UI for previous user ${this.currentUIUserId}`),await this.stopUI()),this.currentUIUserId===e)return o(`UI already running for user ${e}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-t};let n=await this.execute(e,`INSTALL ui; LOAD ui;`);if(!n.success)return o(`Failed to install UI extension: ${n.error.message}`),n;let r=await this.execute(e,`SET ui_local_port = ${this.uiInternalPort}`);if(!r.success)return o(`Failed to set UI port: ${r.error.message}`),r;let i=await this.execute(e,`CALL start_ui_server()`);return i.success?(this.currentUIUserId=e,this.startUIKeepalive(e),o(`UI started for user ${e} on port ${this.uiInternalPort}`),{success:!0,data:{port:this.uiInternalPort},executionTime:Date.now()-t}):(o(`Failed to start UI server: ${i.error.message}`),i)}startUIKeepalive(e){this.stopUIKeepalive(),o(`Starting UI keepalive for user ${e}`),this.uiKeepaliveTimer=setInterval(async()=>{this.pond&&this.currentUIUserId===e&&(o(`UI keepalive ping for user ${e}`),await this.pond.query(e,`SELECT 1`))},this.UI_KEEPALIVE_INTERVAL)}stopUIKeepalive(){this.uiKeepaliveTimer&&(o(`Stopping UI keepalive`),clearInterval(this.uiKeepaliveTimer),this.uiKeepaliveTimer=null)}async stopUI(){if(this.stopUIKeepalive(),!this.currentUIUserId)return o(`No UI running to stop`),{success:!0,data:void 0};if(!this.pond)return this.currentUIUserId=null,{success:!0,data:void 0};o(`Stopping UI for user ${this.currentUIUserId}`);let e=Date.now(),t=await this.execute(this.currentUIUserId,`CALL stop_ui_server()`),n=this.currentUIUserId;return this.currentUIUserId=null,t.success?(o(`UI stopped for user ${n}`),{success:!0,data:void 0,executionTime:Date.now()-e}):(o(`Failed to stop UI: ${t.error.message}`),t)}getCurrentUIUser(){return this.currentUIUserId}setUIPort(e){this.uiInternalPort=e}getUIPort(){return this.uiInternalPort}handleEither(e,t){return e.fold(e=>({success:!1,error:{code:this.mapErrorCode(e.code),message:e.message,details:{originalCode:e.code,context:e.context,cause:e.cause?.message}}}),e=>({success:!0,data:e,executionTime:t}))}mapErrorCode(e){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`}[e]||`INTERNAL_ERROR`}notInitializedError(){return{success:!1,error:{code:`FAILED_PRECONDITION`,message:`DuckPond not initialized. Call init() first.`}}}};export{s as t};
|
|
2
|
-
//# sourceMappingURL=server-core-B66uY2zm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-core-B66uY2zm.js","names":["config: DuckPondServerConfig"],"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 * Extends DuckPondConfig with server-specific options\n */\nexport type DuckPondServerConfig = DuckPondConfig & {\n /** Directory for persistent database storage (default: ~/.duckpond/data) */\n dataDir?: string\n}\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 private uiKeepaliveTimer: ReturnType<typeof setInterval> | null = null\n private readonly UI_KEEPALIVE_INTERVAL = 30000 // 30 seconds\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 this.startUIKeepalive(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 * Start keepalive timer to prevent UI user from being evicted\n */\n private startUIKeepalive(userId: string): void {\n this.stopUIKeepalive()\n log(`Starting UI keepalive for user ${userId}`)\n this.uiKeepaliveTimer = setInterval(async () => {\n if (this.pond && this.currentUIUserId === userId) {\n log(`UI keepalive ping for user ${userId}`)\n await this.pond.query(userId, \"SELECT 1\")\n }\n }, this.UI_KEEPALIVE_INTERVAL)\n }\n\n /**\n * Stop the keepalive timer\n */\n private stopUIKeepalive(): void {\n if (this.uiKeepaliveTimer) {\n log(\"Stopping UI keepalive\")\n clearInterval(this.uiKeepaliveTimer)\n this.uiKeepaliveTimer = null\n }\n }\n\n /**\n * Stop the currently running DuckDB UI\n */\n async stopUI(): Promise<MCPResult<void>> {\n this.stopUIKeepalive()\n\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 as const,\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 as const,\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 {\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AM1B,qBAA+C,CAC7C,MAAO,CACL,QAAS,GACT,MAAO,CACL,KAAM,sBACN,QAAS,+CACV,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./logger-CX5FKgvo.js";import{serve as t}from"@hono/node-server";import{Hono as n}from"hono";const r=e.core;async function i(e){let{port:i,duckpond:a}=e,o=a.getUIPort(),s=new n;s.get(`/ui`,e=>{let t=a.getCurrentUIUser(),n=a.listUsers();return e.json({message:t?`UI active for user: ${t}. Access directly at http://localhost:${o}`:`No UI active. Visit /ui/:userId to start DuckDB UI for a user.`,currentUser:t,uiUrl:t?`http://localhost:${o}`:null,availableUsers:n.success?n.data.users:[]})}),s.get(`/ui/:userId`,async e=>{let t=e.req.param(`userId`);r(`[UI Server] Starting UI for user: ${t}`);let n=await a.startUI(t);return n.success?e.json({success:!0,message:`UI started for user: ${t}`,uiUrl:`http://localhost:${o}`,hint:`Access the DuckDB UI directly at the uiUrl above`}):e.json({error:`Failed to start UI`,message:n.error.message,details:n.error.details},500)}),s.get(`/`,e=>{let t=a.getCurrentUIUser();return e.json({name:`DuckPond UI Server`,description:`Lightweight HTTP server for DuckDB UI access in stdio mode`,currentUIUser:t,uiUrl:t?`http://localhost:${o}`:null,endpoints:{startUI:`http://localhost:${i}/ui/:userId`,status:`http://localhost:${i}/ui`}})}),t({fetch:s.fetch,port:i}),r(`✓ UI server running at http://localhost:${i}/ui`),r(` Visit http://localhost:${i}/ui/:userId to start DuckDB UI`),r(` Then access DuckDB UI directly at http://localhost:${o}`)}export{i as t};
|
|
2
|
-
//# sourceMappingURL=ui-server-BoQ-kekq.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ui-server-BoQ-kekq.js","names":[],"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 starting 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\n app.get(\"/ui\", (c) => {\n const currentUser = duckpond.getCurrentUIUser()\n const listResult = duckpond.listUsers()\n return c.json({\n message: currentUser\n ? `UI active for user: ${currentUser}. Access directly at http://localhost:${uiInternalPort}`\n : \"No UI active. Visit /ui/:userId to start DuckDB UI for a user.\",\n currentUser,\n uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n availableUsers: listResult.success ? listResult.data.users : [],\n })\n })\n\n // GET /ui/:userId - Start UI for a specific user\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 return c.json({\n success: true,\n message: `UI started for user: ${userId}`,\n uiUrl: `http://localhost:${uiInternalPort}`,\n hint: \"Access the DuckDB UI directly at the uiUrl above\",\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 uiUrl: currentUser ? `http://localhost:${uiInternalPort}` : null,\n endpoints: {\n startUI: `http://localhost:${port}/ui/:userId`,\n status: `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 log(` Then access DuckDB UI directly at http://localhost:${uiIn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