duckpond-mcp-server 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib.d.ts +2 -2
- package/dist/server.d.ts +6 -1
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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`,
|
|
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;process.env.DUCKPOND_BEARER_TOKEN&&(c={token:process.env.DUCKPOND_BEARER_TOKEN,userId:process.env.DUCKPOND_BEARER_TOKEN_USER_ID},console.error(`🔐 Bearer token authentication enabled`),c.userId&&console.error(` User ID: ${c.userId}`));let l=e.ui||process.env.DUCKPOND_UI_ENABLED===`true`,d=parseInt(e.uiPort)||4e3,f=parseInt(e.uiInternalPort)||4213;l&&e.transport===`stdio`&&(i?console.error(`🖥️ DuckDB UI will start at http://localhost:${f}`):(console.error(`🖥️ UI management server at http://localhost:${d}/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,bearerToken:c,ui:l?{enabled:!0,port:d,internalPort:f,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":[],"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,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,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,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"}
|
|
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 // Load Bearer Token configuration from environment variables\n let bearerTokenConfig: { token: string; userId?: string } | undefined\n if (process.env.DUCKPOND_BEARER_TOKEN) {\n bearerTokenConfig = {\n token: process.env.DUCKPOND_BEARER_TOKEN,\n userId: process.env.DUCKPOND_BEARER_TOKEN_USER_ID,\n }\n\n console.error(\"🔐 Bearer token authentication enabled\")\n if (bearerTokenConfig.userId) {\n console.error(` User ID: ${bearerTokenConfig.userId}`)\n }\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 bearerToken: bearerTokenConfig,\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,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,CAE3E,EAA+B,CACnC,YAAa,QAAQ,IAAI,uBAAyB,MAClD,QAAS,SAAS,QAAQ,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AkB,QACpB,QAAQ,MAAM,eAAe,EAAkB,SAAS,EAK5D,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,YAAa,EACb,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, StartServerOptions, createFastMCPServer, startServer } from "./server.js";
|
|
2
|
+
import { BearerTokenConfig, FastMCPServerOptions, StartServerOptions, createFastMCPServer, startServer } from "./server.js";
|
|
3
3
|
import { getDefaultUserId } from "./tools/index.js";
|
|
4
|
-
export { DuckPondServer, type DuckPondServerConfig, type FastMCPServerOptions, type StartServerOptions, createFastMCPServer, getDefaultUserId, startServer };
|
|
4
|
+
export { type BearerTokenConfig, DuckPondServer, type DuckPondServerConfig, type FastMCPServerOptions, type StartServerOptions, createFastMCPServer, getDefaultUserId, startServer };
|
package/dist/server.d.ts
CHANGED
|
@@ -11,6 +11,10 @@ type OAuthConfig = {
|
|
|
11
11
|
issuer?: string;
|
|
12
12
|
resource?: string;
|
|
13
13
|
};
|
|
14
|
+
type BearerTokenConfig = {
|
|
15
|
+
token: string;
|
|
16
|
+
userId?: string;
|
|
17
|
+
};
|
|
14
18
|
type FastMCPServerOptions = {
|
|
15
19
|
config: DuckPondServerConfig;
|
|
16
20
|
port?: number;
|
|
@@ -22,6 +26,7 @@ type FastMCPServerOptions = {
|
|
|
22
26
|
userId?: string;
|
|
23
27
|
email?: string;
|
|
24
28
|
};
|
|
29
|
+
bearerToken?: BearerTokenConfig;
|
|
25
30
|
ui?: {
|
|
26
31
|
enabled: boolean;
|
|
27
32
|
port: number;
|
|
@@ -62,5 +67,5 @@ declare function startServer(opts: StartServerOptions): Promise<void>;
|
|
|
62
67
|
/** @deprecated Use object form: startServer({ options, transport, beforeStart }) */
|
|
63
68
|
declare function startServer(options: FastMCPServerOptions, transport: "stdio" | "http"): Promise<void>;
|
|
64
69
|
//#endregion
|
|
65
|
-
export { FastMCPServerOptions, OAuthConfig, StartServerOptions, createFastMCPServer, startServer };
|
|
70
|
+
export { BearerTokenConfig, FastMCPServerOptions, OAuthConfig, StartServerOptions, createFastMCPServer, startServer };
|
|
66
71
|
//# sourceMappingURL=server.d.ts.map
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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=`
|
|
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||e.bearerToken?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.bearerToken&&n.startsWith(`Bearer `)){if(n.slice(7)===e.bearerToken.token)return Promise.resolve({userId:e.bearerToken.userId||`bearer-user`,email:``,scope:`read write`});if(!e.oauth?.enabled)throw new Response(JSON.stringify({error:`invalid_token`,error_description:`Invalid bearer token`}),{status:401,statusText:`Unauthorized`,headers:{"Content-Type":`application/json`,"WWW-Authenticate":`Bearer realm="MCP", error="invalid_token"`}})}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,bearerToken:!!e.bearerToken}},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>
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,E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,aAAa,CAIzC,IAAc,QAOhB,IANA,MAAM,EAAO,MAAM,CACjB,cAAe,QAChB,CAAC,CACF,EAAI,gDAAgD,CAGhD,EAAQ,IAAI,QACd,GAAI,EAAQ,GAAG,cAAe,CAE5B,EAAI,8BAA8B,EAAQ,GAAG,gBAAgB,CAC7D,IAAM,EAAW,MAAM,EAAS,QAAQ,EAAQ,GAAG,cAAc,CAC7D,EAAS,QACX,QAAQ,MAAM,8CAA8C,EAAS,WAAW,GAAG,CAEnF,EAAI,4BAA4B,EAAS,MAAM,UAAU,MAI3D,MAAM,EAAc,CAClB,KAAM,EAAQ,GAAG,KACjB,WACD,CAAC,MAIN,MAAM,EAAO,MAAM,CACjB,cAAe,aACf,WAAY,CACV,KAAM,EAAQ,MAAQ,IACtB,SAAW,EAAQ,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"}
|
|
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 BearerTokenConfig = {\n token: string\n userId?: 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 bearerToken?: BearerTokenConfig\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, Bearer Token, or none)\n const server =\n options.oauth?.enabled || options.basicAuth || options.bearerToken\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 static Bearer Token authentication\n if (options.bearerToken && authHeader.startsWith(\"Bearer \")) {\n const token = authHeader.slice(7)\n\n if (token === options.bearerToken.token) {\n return Promise.resolve({\n userId: options.bearerToken.userId || \"bearer-user\",\n email: \"\",\n scope: \"read write\",\n })\n }\n\n // If bearer token is configured but doesn't match, and OAuth is not enabled, reject\n if (!options.oauth?.enabled) {\n throw new Response(\n JSON.stringify({\n error: \"invalid_token\",\n error_description: \"Invalid bearer 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\"`,\n },\n },\n )\n }\n\n // Fall through to OAuth JWT validation if OAuth is also enabled\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 bearerToken: !!options.bearerToken,\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,QAsCd,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,WAAa,EAAQ,YACnD,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,MAAO,cACtF,QAAS,GAAG,EAAQ,OAAO,QAAU,oBAAoB,EAAQ,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AAe,CAE5B,EAAI,8BAA8B,EAAQ,GAAG,gBAAgB,CAC7D,IAAM,EAAW,MAAM,EAAS,QAAQ,EAAQ,GAAG,cAAc,CAC7D,EAAS,QACX,QAAQ,MAAM,8CAA8C,EAAS,WAAW,GAAG,CAEnF,EAAI,4BAA4B,EAAS,MAAM,UAAU,MAI3D,MAAM,EAAc,CAClB,KAAM,EAAQ,GAAG,KACjB,WACD,CAAC,MAIN,MAAM,EAAO,MAAM,CACjB,cAAe,aACf,WAAY,CACV,KAAM,EAAQ,MAAQ,IACtB,SAAW,EAAQ,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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "duckpond-mcp-server",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"description": "MCP server for multi-tenant DuckDB management with R2/S3 storage",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@hono/node-server": "^1.19.9",
|
|
46
|
-
"fastmcp": "3.
|
|
46
|
+
"fastmcp": "3.33.0",
|
|
47
47
|
"@types/express": "^5.0.6",
|
|
48
48
|
"@types/jsonwebtoken": "^9.0.10",
|
|
49
49
|
"commander": "^14.0.3",
|