@studiometa/productive-mcp 0.10.10 → 0.10.12

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.
Files changed (74) hide show
  1. package/README.md +120 -0
  2. package/dist/api-reference/generated.d.ts +3 -0
  3. package/dist/api-reference/generated.d.ts.map +1 -0
  4. package/dist/api-reference/types.d.ts +31 -0
  5. package/dist/api-reference/types.d.ts.map +1 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/crypto.js +3 -3
  8. package/dist/crypto.js.map +1 -1
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/handlers/activities.d.ts +3 -99
  11. package/dist/handlers/activities.d.ts.map +1 -1
  12. package/dist/handlers/api-read.d.ts +14 -0
  13. package/dist/handlers/api-read.d.ts.map +1 -0
  14. package/dist/handlers/api-utils.d.ts +27 -0
  15. package/dist/handlers/api-utils.d.ts.map +1 -0
  16. package/dist/handlers/api-write.d.ts +10 -0
  17. package/dist/handlers/api-write.d.ts.map +1 -0
  18. package/dist/handlers/attachments.d.ts +3 -99
  19. package/dist/handlers/attachments.d.ts.map +1 -1
  20. package/dist/handlers/bookings.d.ts +3 -99
  21. package/dist/handlers/bookings.d.ts.map +1 -1
  22. package/dist/handlers/comments.d.ts +3 -99
  23. package/dist/handlers/comments.d.ts.map +1 -1
  24. package/dist/handlers/companies.d.ts +3 -99
  25. package/dist/handlers/companies.d.ts.map +1 -1
  26. package/dist/handlers/custom-fields.d.ts +3 -99
  27. package/dist/handlers/custom-fields.d.ts.map +1 -1
  28. package/dist/handlers/deals.d.ts +3 -99
  29. package/dist/handlers/deals.d.ts.map +1 -1
  30. package/dist/handlers/discussions.d.ts +3 -99
  31. package/dist/handlers/discussions.d.ts.map +1 -1
  32. package/dist/handlers/index.d.ts.map +1 -1
  33. package/dist/handlers/pages.d.ts +3 -99
  34. package/dist/handlers/pages.d.ts.map +1 -1
  35. package/dist/handlers/projects.d.ts +3 -99
  36. package/dist/handlers/projects.d.ts.map +1 -1
  37. package/dist/handlers/search.d.ts +1 -1
  38. package/dist/handlers/search.d.ts.map +1 -1
  39. package/dist/handlers/services.d.ts +3 -99
  40. package/dist/handlers/services.d.ts.map +1 -1
  41. package/dist/handlers/tasks.d.ts +3 -99
  42. package/dist/handlers/tasks.d.ts.map +1 -1
  43. package/dist/handlers/time.d.ts +3 -99
  44. package/dist/handlers/time.d.ts.map +1 -1
  45. package/dist/handlers/timers.d.ts +3 -99
  46. package/dist/handlers/timers.d.ts.map +1 -1
  47. package/dist/handlers-DonE83xo.js +41289 -0
  48. package/dist/handlers-DonE83xo.js.map +1 -0
  49. package/dist/handlers.js +1 -1
  50. package/dist/http-QQVUnV2e.js +3238 -0
  51. package/dist/http-QQVUnV2e.js.map +1 -0
  52. package/dist/http.d.ts.map +1 -1
  53. package/dist/http.js +1 -1
  54. package/dist/index.js +2 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/oauth.js.map +1 -1
  57. package/dist/schema.d.ts +32 -1
  58. package/dist/schema.d.ts.map +1 -1
  59. package/dist/server.js +2 -2
  60. package/dist/server.js.map +1 -1
  61. package/dist/{stdio-BFK9AcdQ.js → stdio-CRD2nJPs.js} +2 -2
  62. package/dist/{stdio-BFK9AcdQ.js.map → stdio-CRD2nJPs.js.map} +1 -1
  63. package/dist/stdio.js +1 -1
  64. package/dist/tools.d.ts.map +1 -1
  65. package/dist/tools.js +193 -119
  66. package/dist/tools.js.map +1 -1
  67. package/dist/{version-Cy8UEAT1.js → version-DMEaGciu.js} +3 -3
  68. package/dist/{version-Cy8UEAT1.js.map → version-DMEaGciu.js.map} +1 -1
  69. package/package.json +6 -6
  70. package/skills/SKILL.md +113 -1
  71. package/dist/handlers-vtRpc-Lx.js +0 -4301
  72. package/dist/handlers-vtRpc-Lx.js.map +0 -1
  73. package/dist/http-CVE4qtko.js +0 -6541
  74. package/dist/http-CVE4qtko.js.map +0 -1
package/dist/oauth.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","names":[],"sources":["../src/oauth.ts"],"sourcesContent":["/**\n * OAuth 2.0 endpoints for Claude Desktop integration\n *\n * Implements OAuth 2.1 with PKCE as specified in the MCP authorization spec.\n * Uses stateless encrypted tokens - no server-side storage required.\n *\n * Spec: https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization\n *\n * Flow:\n * 1. Claude redirects user to /authorize with OAuth params (including PKCE)\n * 2. User enters Productive credentials in login form\n * 3. Server encrypts credentials + PKCE challenge into authorization code\n * 4. Redirects back to Claude with the code\n * 5. Claude exchanges code for access token via /token (with code_verifier)\n * 6. Server validates PKCE and returns access token\n */\n\nimport { defineHandler, getQuery, redirect, type H3Event } from 'h3';\nimport { createHash } from 'node:crypto';\n\nimport { createAuthToken } from './auth.js';\nimport { createAuthCode, decodeAuthCode } from './crypto.js';\n\n/**\n * OAuth metadata for discovery (RFC 8414)\n * GET /.well-known/oauth-authorization-server\n *\n * MCP clients MUST check this endpoint first for server capabilities.\n */\nexport const oauthMetadataHandler = defineHandler((event: H3Event) => {\n const host = event.req.headers.get('host') || 'localhost:3000';\n const protocol = event.req.headers.get('x-forwarded-proto') || 'http';\n const baseUrl = `${protocol}://${host}`;\n\n event.res.headers.set('Content-Type', 'application/json');\n event.res.headers.set('Cache-Control', 'public, max-age=3600');\n\n return {\n // Required fields per RFC 8414\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/authorize`,\n token_endpoint: `${baseUrl}/token`,\n response_types_supported: ['code'],\n\n // OAuth 2.1 / MCP requirements\n grant_types_supported: ['authorization_code', 'refresh_token'],\n code_challenge_methods_supported: ['S256'],\n token_endpoint_auth_methods_supported: ['none'], // Public client\n\n // Optional but useful\n registration_endpoint: `${baseUrl}/register`,\n scopes_supported: ['productive'],\n service_documentation: 'https://github.com/studiometa/productive-tools',\n };\n});\n\n/**\n * Dynamic Client Registration endpoint (RFC 7591)\n * POST /register\n *\n * MCP servers SHOULD support DCR to allow clients to register automatically.\n * Since we use stateless tokens, we accept any registration and return\n * a generated client_id.\n */\nexport const registerHandler = defineHandler(async (event: H3Event) => {\n event.res.headers.set('Content-Type', 'application/json');\n\n let body: Record<string, unknown>;\n try {\n body = (await event.req.json()) as Record<string, unknown>;\n } catch {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Invalid JSON body',\n };\n }\n\n // Extract client metadata\n const clientName = (body.client_name as string) || 'MCP Client';\n const redirectUris = (body.redirect_uris as string[]) || [];\n\n // Generate a client_id based on the registration\n // Since we're stateless, we encode minimal info in the client_id\n const clientId = Buffer.from(\n JSON.stringify({\n name: clientName,\n ts: Date.now(),\n }),\n ).toString('base64url');\n\n event.res.status = 201;\n return {\n client_id: clientId,\n client_name: clientName,\n redirect_uris: redirectUris,\n token_endpoint_auth_method: 'none',\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n };\n});\n\n/**\n * Authorization endpoint - shows login form\n * GET /authorize\n */\nexport const authorizeGetHandler = defineHandler((event: H3Event) => {\n const query = getQuery(event);\n\n // Extract OAuth parameters\n const clientId = query.client_id as string;\n const redirectUri = query.redirect_uri as string;\n const state = query.state as string;\n const codeChallenge = query.code_challenge as string;\n const codeChallengeMethod = query.code_challenge_method as string;\n const scope = query.scope as string;\n\n // Validate required parameters per OAuth 2.1\n if (!redirectUri) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n event.res.status = 400;\n return renderErrorPage('Missing required parameter: redirect_uri');\n }\n\n // PKCE is REQUIRED for public clients per MCP spec\n if (!codeChallenge) {\n // Redirect back with error per OAuth spec\n const errorUrl = new URL(redirectUri);\n errorUrl.searchParams.set('error', 'invalid_request');\n errorUrl.searchParams.set('error_description', 'code_challenge is required');\n if (state) errorUrl.searchParams.set('state', state);\n return redirect(errorUrl.toString());\n }\n\n if (codeChallengeMethod && codeChallengeMethod !== 'S256') {\n const errorUrl = new URL(redirectUri);\n errorUrl.searchParams.set('error', 'invalid_request');\n errorUrl.searchParams.set('error_description', 'Only S256 code_challenge_method is supported');\n if (state) errorUrl.searchParams.set('state', state);\n return redirect(errorUrl.toString());\n }\n\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n\n // Render login form\n return renderLoginForm({\n clientId,\n redirectUri,\n state,\n codeChallenge,\n codeChallengeMethod: codeChallengeMethod || 'S256',\n scope,\n });\n});\n\n/**\n * Authorization endpoint - process login\n * POST /authorize\n */\nexport const authorizePostHandler = defineHandler(async (event: H3Event) => {\n const formData = await event.req.formData();\n const body = Object.fromEntries(formData.entries()) as Record<string, string>;\n\n const { orgId, apiToken, userId, redirectUri, state, codeChallenge, codeChallengeMethod } = body;\n\n // Validate redirect URI first (security requirement)\n if (!redirectUri) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n event.res.status = 400;\n return renderErrorPage('Missing redirect_uri parameter');\n }\n\n // Validate redirect URI format (must be HTTPS or localhost)\n try {\n const uri = new URL(redirectUri);\n const isLocalhost = uri.hostname === 'localhost' || uri.hostname === '127.0.0.1';\n const isHttps = uri.protocol === 'https:';\n if (!isLocalhost && !isHttps) {\n event.res.status = 400;\n return renderErrorPage('redirect_uri must be HTTPS or localhost');\n }\n } catch {\n event.res.status = 400;\n return renderErrorPage('Invalid redirect_uri format');\n }\n\n // Validate required credentials\n if (!orgId || !apiToken) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n return renderLoginForm({\n redirectUri,\n state,\n codeChallenge,\n codeChallengeMethod,\n error: 'Organization ID and API Token are required',\n });\n }\n\n // Create encrypted authorization code with PKCE challenge\n const code = createAuthCode({\n orgId,\n apiToken,\n userId: userId || undefined,\n codeChallenge,\n codeChallengeMethod: codeChallengeMethod || 'S256',\n });\n\n // Build redirect URL 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 // Redirect back to the OAuth client with the authorization code.\n // Strict OAuth clients may not follow HTML/meta-refresh or JavaScript redirects.\n return redirect(redirectUrl.toString());\n});\n\n/**\n * Token endpoint - exchange code for access token\n * POST /token\n *\n * Supports:\n * - authorization_code grant (with PKCE validation)\n * - refresh_token grant\n */\nexport const tokenHandler = defineHandler(async (event: H3Event) => {\n event.res.headers.set('Content-Type', 'application/json');\n\n let body: Record<string, string>;\n const contentType = event.req.headers.get('content-type') || '';\n\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const rawText = await event.req.text();\n body = Object.fromEntries(new URLSearchParams(rawText));\n } else {\n body = (await event.req.json()) as Record<string, string>;\n }\n\n const { grant_type, code, code_verifier, refresh_token } = body;\n\n // Handle refresh token grant\n if (grant_type === 'refresh_token') {\n return handleRefreshToken(event, refresh_token);\n }\n\n // Validate authorization code grant\n if (grant_type !== 'authorization_code') {\n event.res.status = 400;\n return {\n error: 'unsupported_grant_type',\n error_description: 'Supported grant types: authorization_code, refresh_token',\n };\n }\n\n if (!code) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing authorization code',\n };\n }\n\n if (!code_verifier) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing code_verifier (PKCE required)',\n };\n }\n\n try {\n // Decode the authorization code\n const payload = decodeAuthCode(code);\n\n // Validate PKCE: SHA256(code_verifier) must equal code_challenge\n if (payload.codeChallenge) {\n const expectedChallenge = createS256Challenge(code_verifier);\n if (expectedChallenge !== payload.codeChallenge) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: 'Invalid code_verifier',\n };\n }\n }\n\n // Create access token (base64 encoded credentials)\n const accessToken = createAuthToken({\n organizationId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n });\n\n // Create refresh token (encrypted credentials, longer expiry)\n const refreshToken = createAuthCode(\n {\n orgId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n },\n 86400 * 30, // 30 days\n );\n\n return {\n access_token: accessToken,\n token_type: 'Bearer',\n expires_in: 3600, // 1 hour (access tokens should be short-lived)\n refresh_token: refreshToken,\n };\n } catch (error) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: error instanceof Error ? error.message : 'Invalid authorization code',\n };\n }\n});\n\n/**\n * Handle refresh token grant\n */\nfunction handleRefreshToken(event: H3Event, refreshToken: string | undefined) {\n if (!refreshToken) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing refresh_token',\n };\n }\n\n try {\n // Decode refresh token (it's just an encrypted auth code with longer expiry)\n const payload = decodeAuthCode(refreshToken);\n\n // Create new access token\n const accessToken = createAuthToken({\n organizationId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n });\n\n // Create new refresh token (rotate for security)\n const newRefreshToken = createAuthCode(\n {\n orgId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n },\n 86400 * 30, // 30 days\n );\n\n return {\n access_token: accessToken,\n token_type: 'Bearer',\n expires_in: 3600,\n refresh_token: newRefreshToken,\n };\n } catch (error) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: error instanceof Error ? error.message : 'Invalid refresh token',\n };\n }\n}\n\n/**\n * Create S256 PKCE challenge from verifier\n * SHA256(code_verifier) encoded as base64url\n */\nfunction createS256Challenge(codeVerifier: string): string {\n return createHash('sha256').update(codeVerifier).digest('base64url');\n}\n\n/**\n * Render the login form HTML\n */\nfunction renderLoginForm(params: {\n clientId?: string;\n redirectUri?: string;\n state?: string;\n codeChallenge?: string;\n codeChallengeMethod?: string;\n scope?: string;\n error?: string;\n}): string {\n const { redirectUri, state, codeChallenge, codeChallengeMethod, error } = params;\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Connect to Productive.io</title>\n <style>\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n }\n .container {\n background: white;\n border-radius: 16px;\n box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n padding: 40px;\n width: 100%;\n max-width: 420px;\n }\n .logo {\n text-align: center;\n margin-bottom: 24px;\n }\n .logo svg {\n width: 48px;\n height: 48px;\n }\n h1 {\n text-align: center;\n color: #1a1a2e;\n font-size: 24px;\n margin-bottom: 8px;\n }\n .subtitle {\n text-align: center;\n color: #666;\n font-size: 14px;\n margin-bottom: 32px;\n }\n .error {\n background: #fee2e2;\n border: 1px solid #fecaca;\n color: #dc2626;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 24px;\n font-size: 14px;\n }\n .form-group {\n margin-bottom: 20px;\n }\n label {\n display: block;\n font-size: 14px;\n font-weight: 500;\n color: #374151;\n margin-bottom: 6px;\n }\n input {\n width: 100%;\n padding: 12px 16px;\n border: 1px solid #d1d5db;\n border-radius: 8px;\n font-size: 16px;\n transition: border-color 0.2s, box-shadow 0.2s;\n }\n input:focus {\n outline: none;\n border-color: #667eea;\n box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);\n }\n input::placeholder {\n color: #9ca3af;\n }\n .help-text {\n font-size: 12px;\n color: #6b7280;\n margin-top: 4px;\n }\n button {\n width: 100%;\n padding: 14px 24px;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: transform 0.2s, box-shadow 0.2s;\n }\n button:hover {\n transform: translateY(-1px);\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n }\n button:active {\n transform: translateY(0);\n }\n .footer {\n text-align: center;\n margin-top: 24px;\n font-size: 12px;\n color: #9ca3af;\n }\n .footer a {\n color: #667eea;\n text-decoration: none;\n }\n .footer a:hover {\n text-decoration: underline;\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"logo\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M12 2L2 7L12 12L22 7L12 2Z\" stroke=\"#667eea\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n <path d=\"M2 17L12 22L22 17\" stroke=\"#764ba2\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n <path d=\"M2 12L12 17L22 12\" stroke=\"#667eea\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </div>\n <h1>Connect to Productive.io</h1>\n <p class=\"subtitle\">Enter your Productive.io credentials to connect with Claude</p>\n \n ${error ? `<div class=\"error\">${escapeHtml(error)}</div>` : ''}\n \n <form method=\"POST\" action=\"/authorize\">\n <input type=\"hidden\" name=\"redirectUri\" value=\"${escapeHtml(redirectUri || '')}\">\n <input type=\"hidden\" name=\"state\" value=\"${escapeHtml(state || '')}\">\n <input type=\"hidden\" name=\"codeChallenge\" value=\"${escapeHtml(codeChallenge || '')}\">\n <input type=\"hidden\" name=\"codeChallengeMethod\" value=\"${escapeHtml(codeChallengeMethod || 'S256')}\">\n \n <div class=\"form-group\">\n <label for=\"orgId\">Organization ID *</label>\n <input type=\"text\" id=\"orgId\" name=\"orgId\" required placeholder=\"e.g., 12345\">\n <p class=\"help-text\">Found in Settings → API integrations</p>\n </div>\n \n <div class=\"form-group\">\n <label for=\"apiToken\">API Token *</label>\n <input type=\"password\" id=\"apiToken\" name=\"apiToken\" required placeholder=\"pk_...\">\n <p class=\"help-text\">Generate at Settings → API integrations → Generate new token</p>\n </div>\n \n <div class=\"form-group\">\n <label for=\"userId\">User ID (optional)</label>\n <input type=\"text\" id=\"userId\" name=\"userId\" placeholder=\"e.g., 67890\">\n <p class=\"help-text\">Required for creating time entries. Found in your profile URL.</p>\n </div>\n \n <button type=\"submit\">Connect to Productive</button>\n </form>\n \n <p class=\"footer\">\n Your credentials are encrypted and sent directly to Claude.<br>\n <a href=\"https://developer.productive.io\" target=\"_blank\">Productive.io API Documentation</a>\n </p>\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Render error page\n */\nfunction renderErrorPage(message: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Error - Productive MCP</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #f3f4f6;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n }\n .container {\n background: white;\n border-radius: 16px;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n padding: 40px;\n text-align: center;\n max-width: 400px;\n }\n h1 {\n color: #dc2626;\n margin-bottom: 16px;\n }\n p {\n color: #6b7280;\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>Error</h1>\n <p>${escapeHtml(message)}</p>\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Escape HTML special characters\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#039;');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,uBAAuB,eAAe,UAAmB;CACpE,MAAM,OAAO,MAAM,IAAI,QAAQ,IAAI,OAAO,IAAI;CAE9C,MAAM,UAAU,GADC,MAAM,IAAI,QAAQ,IAAI,oBAAoB,IAAI,OACnC,KAAK;AAEjC,OAAM,IAAI,QAAQ,IAAI,gBAAgB,mBAAmB;AACzD,OAAM,IAAI,QAAQ,IAAI,iBAAiB,uBAAuB;AAE9D,QAAO;EAEL,QAAQ;EACR,wBAAwB,GAAG,QAAQ;EACnC,gBAAgB,GAAG,QAAQ;EAC3B,0BAA0B,CAAC,OAAO;EAGlC,uBAAuB,CAAC,sBAAsB,gBAAgB;EAC9D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AC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCzG,SAAS,gBAAgB,SAAyB;AAChD,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAoCA,WAAW,QAAQ,CAAC;;;;;;;;AAS7B,SAAS,WAAW,KAAqB;AACvC,QAAO,IACJ,QAAQ,MAAM,QAAQ,CACtB,QAAQ,MAAM,OAAO,CACrB,QAAQ,MAAM,OAAO,CACrB,QAAQ,MAAM,SAAS,CACvB,QAAQ,MAAM,SAAS"}
1
+ {"version":3,"file":"oauth.js","names":[],"sources":["../src/oauth.ts"],"sourcesContent":["/**\n * OAuth 2.0 endpoints for Claude Desktop integration\n *\n * Implements OAuth 2.1 with PKCE as specified in the MCP authorization spec.\n * Uses stateless encrypted tokens - no server-side storage required.\n *\n * Spec: https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization\n *\n * Flow:\n * 1. Claude redirects user to /authorize with OAuth params (including PKCE)\n * 2. User enters Productive credentials in login form\n * 3. Server encrypts credentials + PKCE challenge into authorization code\n * 4. Redirects back to Claude with the code\n * 5. Claude exchanges code for access token via /token (with code_verifier)\n * 6. Server validates PKCE and returns access token\n */\n\nimport { defineHandler, getQuery, redirect, type H3Event } from 'h3';\nimport { createHash } from 'node:crypto';\n\nimport { createAuthToken } from './auth.js';\nimport { createAuthCode, decodeAuthCode } from './crypto.js';\n\n/**\n * OAuth metadata for discovery (RFC 8414)\n * GET /.well-known/oauth-authorization-server\n *\n * MCP clients MUST check this endpoint first for server capabilities.\n */\nexport const oauthMetadataHandler = defineHandler((event: H3Event) => {\n const host = event.req.headers.get('host') || 'localhost:3000';\n const protocol = event.req.headers.get('x-forwarded-proto') || 'http';\n const baseUrl = `${protocol}://${host}`;\n\n event.res.headers.set('Content-Type', 'application/json');\n event.res.headers.set('Cache-Control', 'public, max-age=3600');\n\n return {\n // Required fields per RFC 8414\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/authorize`,\n token_endpoint: `${baseUrl}/token`,\n response_types_supported: ['code'],\n\n // OAuth 2.1 / MCP requirements\n grant_types_supported: ['authorization_code', 'refresh_token'],\n code_challenge_methods_supported: ['S256'],\n token_endpoint_auth_methods_supported: ['none'], // Public client\n\n // Optional but useful\n registration_endpoint: `${baseUrl}/register`,\n scopes_supported: ['productive'],\n service_documentation: 'https://github.com/studiometa/productive-tools',\n };\n});\n\n/**\n * Dynamic Client Registration endpoint (RFC 7591)\n * POST /register\n *\n * MCP servers SHOULD support DCR to allow clients to register automatically.\n * Since we use stateless tokens, we accept any registration and return\n * a generated client_id.\n */\nexport const registerHandler = defineHandler(async (event: H3Event) => {\n event.res.headers.set('Content-Type', 'application/json');\n\n let body: Record<string, unknown>;\n try {\n body = (await event.req.json()) as Record<string, unknown>;\n } catch {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Invalid JSON body',\n };\n }\n\n // Extract client metadata\n const clientName = (body.client_name as string) || 'MCP Client';\n const redirectUris = (body.redirect_uris as string[]) || [];\n\n // Generate a client_id based on the registration\n // Since we're stateless, we encode minimal info in the client_id\n const clientId = Buffer.from(\n JSON.stringify({\n name: clientName,\n ts: Date.now(),\n }),\n ).toString('base64url');\n\n event.res.status = 201;\n return {\n client_id: clientId,\n client_name: clientName,\n redirect_uris: redirectUris,\n token_endpoint_auth_method: 'none',\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n };\n});\n\n/**\n * Authorization endpoint - shows login form\n * GET /authorize\n */\nexport const authorizeGetHandler = defineHandler((event: H3Event) => {\n const query = getQuery(event);\n\n // Extract OAuth parameters\n const clientId = query.client_id as string;\n const redirectUri = query.redirect_uri as string;\n const state = query.state as string;\n const codeChallenge = query.code_challenge as string;\n const codeChallengeMethod = query.code_challenge_method as string;\n const scope = query.scope as string;\n\n // Validate required parameters per OAuth 2.1\n if (!redirectUri) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n event.res.status = 400;\n return renderErrorPage('Missing required parameter: redirect_uri');\n }\n\n // PKCE is REQUIRED for public clients per MCP spec\n if (!codeChallenge) {\n // Redirect back with error per OAuth spec\n const errorUrl = new URL(redirectUri);\n errorUrl.searchParams.set('error', 'invalid_request');\n errorUrl.searchParams.set('error_description', 'code_challenge is required');\n if (state) errorUrl.searchParams.set('state', state);\n return redirect(errorUrl.toString());\n }\n\n if (codeChallengeMethod && codeChallengeMethod !== 'S256') {\n const errorUrl = new URL(redirectUri);\n errorUrl.searchParams.set('error', 'invalid_request');\n errorUrl.searchParams.set('error_description', 'Only S256 code_challenge_method is supported');\n if (state) errorUrl.searchParams.set('state', state);\n return redirect(errorUrl.toString());\n }\n\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n\n // Render login form\n return renderLoginForm({\n clientId,\n redirectUri,\n state,\n codeChallenge,\n codeChallengeMethod: codeChallengeMethod || 'S256',\n scope,\n });\n});\n\n/**\n * Authorization endpoint - process login\n * POST /authorize\n */\nexport const authorizePostHandler = defineHandler(async (event: H3Event) => {\n const formData = await event.req.formData();\n const body = Object.fromEntries(formData.entries()) as Record<string, string>;\n\n const { orgId, apiToken, userId, redirectUri, state, codeChallenge, codeChallengeMethod } = body;\n\n // Validate redirect URI first (security requirement)\n if (!redirectUri) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n event.res.status = 400;\n return renderErrorPage('Missing redirect_uri parameter');\n }\n\n // Validate redirect URI format (must be HTTPS or localhost)\n try {\n const uri = new URL(redirectUri);\n const isLocalhost = uri.hostname === 'localhost' || uri.hostname === '127.0.0.1';\n const isHttps = uri.protocol === 'https:';\n if (!isLocalhost && !isHttps) {\n event.res.status = 400;\n return renderErrorPage('redirect_uri must be HTTPS or localhost');\n }\n } catch {\n event.res.status = 400;\n return renderErrorPage('Invalid redirect_uri format');\n }\n\n // Validate required credentials\n if (!orgId || !apiToken) {\n event.res.headers.set('Content-Type', 'text/html; charset=utf-8');\n return renderLoginForm({\n redirectUri,\n state,\n codeChallenge,\n codeChallengeMethod,\n error: 'Organization ID and API Token are required',\n });\n }\n\n // Create encrypted authorization code with PKCE challenge\n const code = createAuthCode({\n orgId,\n apiToken,\n userId: userId || undefined,\n codeChallenge,\n codeChallengeMethod: codeChallengeMethod || 'S256',\n });\n\n // Build redirect URL 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 // Redirect back to the OAuth client with the authorization code.\n // Strict OAuth clients may not follow HTML/meta-refresh or JavaScript redirects.\n return redirect(redirectUrl.toString());\n});\n\n/**\n * Token endpoint - exchange code for access token\n * POST /token\n *\n * Supports:\n * - authorization_code grant (with PKCE validation)\n * - refresh_token grant\n */\nexport const tokenHandler = defineHandler(async (event: H3Event) => {\n event.res.headers.set('Content-Type', 'application/json');\n\n let body: Record<string, string>;\n const contentType = event.req.headers.get('content-type') || '';\n\n if (contentType.includes('application/x-www-form-urlencoded')) {\n const rawText = await event.req.text();\n body = Object.fromEntries(new URLSearchParams(rawText));\n } else {\n body = (await event.req.json()) as Record<string, string>;\n }\n\n const { grant_type, code, code_verifier, refresh_token } = body;\n\n // Handle refresh token grant\n if (grant_type === 'refresh_token') {\n return handleRefreshToken(event, refresh_token);\n }\n\n // Validate authorization code grant\n if (grant_type !== 'authorization_code') {\n event.res.status = 400;\n return {\n error: 'unsupported_grant_type',\n error_description: 'Supported grant types: authorization_code, refresh_token',\n };\n }\n\n if (!code) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing authorization code',\n };\n }\n\n if (!code_verifier) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing code_verifier (PKCE required)',\n };\n }\n\n try {\n // Decode the authorization code\n const payload = decodeAuthCode(code);\n\n // Validate PKCE: SHA256(code_verifier) must equal code_challenge\n if (payload.codeChallenge) {\n const expectedChallenge = createS256Challenge(code_verifier);\n if (expectedChallenge !== payload.codeChallenge) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: 'Invalid code_verifier',\n };\n }\n }\n\n // Create access token (base64 encoded credentials)\n const accessToken = createAuthToken({\n organizationId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n });\n\n // Create refresh token (encrypted credentials, longer expiry)\n const refreshToken = createAuthCode(\n {\n orgId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n },\n 86400 * 30, // 30 days\n );\n\n return {\n access_token: accessToken,\n token_type: 'Bearer',\n expires_in: 3600, // 1 hour (access tokens should be short-lived)\n refresh_token: refreshToken,\n };\n } catch (error) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: error instanceof Error ? error.message : 'Invalid authorization code',\n };\n }\n});\n\n/**\n * Handle refresh token grant\n */\nfunction handleRefreshToken(event: H3Event, refreshToken: string | undefined) {\n if (!refreshToken) {\n event.res.status = 400;\n return {\n error: 'invalid_request',\n error_description: 'Missing refresh_token',\n };\n }\n\n try {\n // Decode refresh token (it's just an encrypted auth code with longer expiry)\n const payload = decodeAuthCode(refreshToken);\n\n // Create new access token\n const accessToken = createAuthToken({\n organizationId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n });\n\n // Create new refresh token (rotate for security)\n const newRefreshToken = createAuthCode(\n {\n orgId: payload.orgId,\n apiToken: payload.apiToken,\n userId: payload.userId,\n },\n 86400 * 30, // 30 days\n );\n\n return {\n access_token: accessToken,\n token_type: 'Bearer',\n expires_in: 3600,\n refresh_token: newRefreshToken,\n };\n } catch (error) {\n event.res.status = 400;\n return {\n error: 'invalid_grant',\n error_description: error instanceof Error ? error.message : 'Invalid refresh token',\n };\n }\n}\n\n/**\n * Create S256 PKCE challenge from verifier\n * SHA256(code_verifier) encoded as base64url\n */\nfunction createS256Challenge(codeVerifier: string): string {\n return createHash('sha256').update(codeVerifier).digest('base64url');\n}\n\n/**\n * Render the login form HTML\n */\nfunction renderLoginForm(params: {\n clientId?: string;\n redirectUri?: string;\n state?: string;\n codeChallenge?: string;\n codeChallengeMethod?: string;\n scope?: string;\n error?: string;\n}): string {\n const { redirectUri, state, codeChallenge, codeChallengeMethod, error } = params;\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Connect to Productive.io</title>\n <style>\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n }\n .container {\n background: white;\n border-radius: 16px;\n box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n padding: 40px;\n width: 100%;\n max-width: 420px;\n }\n .logo {\n text-align: center;\n margin-bottom: 24px;\n }\n .logo svg {\n width: 48px;\n height: 48px;\n }\n h1 {\n text-align: center;\n color: #1a1a2e;\n font-size: 24px;\n margin-bottom: 8px;\n }\n .subtitle {\n text-align: center;\n color: #666;\n font-size: 14px;\n margin-bottom: 32px;\n }\n .error {\n background: #fee2e2;\n border: 1px solid #fecaca;\n color: #dc2626;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 24px;\n font-size: 14px;\n }\n .form-group {\n margin-bottom: 20px;\n }\n label {\n display: block;\n font-size: 14px;\n font-weight: 500;\n color: #374151;\n margin-bottom: 6px;\n }\n input {\n width: 100%;\n padding: 12px 16px;\n border: 1px solid #d1d5db;\n border-radius: 8px;\n font-size: 16px;\n transition: border-color 0.2s, box-shadow 0.2s;\n }\n input:focus {\n outline: none;\n border-color: #667eea;\n box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);\n }\n input::placeholder {\n color: #9ca3af;\n }\n .help-text {\n font-size: 12px;\n color: #6b7280;\n margin-top: 4px;\n }\n button {\n width: 100%;\n padding: 14px 24px;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: transform 0.2s, box-shadow 0.2s;\n }\n button:hover {\n transform: translateY(-1px);\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n }\n button:active {\n transform: translateY(0);\n }\n .footer {\n text-align: center;\n margin-top: 24px;\n font-size: 12px;\n color: #9ca3af;\n }\n .footer a {\n color: #667eea;\n text-decoration: none;\n }\n .footer a:hover {\n text-decoration: underline;\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"logo\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M12 2L2 7L12 12L22 7L12 2Z\" stroke=\"#667eea\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n <path d=\"M2 17L12 22L22 17\" stroke=\"#764ba2\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n <path d=\"M2 12L12 17L22 12\" stroke=\"#667eea\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </div>\n <h1>Connect to Productive.io</h1>\n <p class=\"subtitle\">Enter your Productive.io credentials to connect with Claude</p>\n \n ${error ? `<div class=\"error\">${escapeHtml(error)}</div>` : ''}\n \n <form method=\"POST\" action=\"/authorize\">\n <input type=\"hidden\" name=\"redirectUri\" value=\"${escapeHtml(redirectUri || '')}\">\n <input type=\"hidden\" name=\"state\" value=\"${escapeHtml(state || '')}\">\n <input type=\"hidden\" name=\"codeChallenge\" value=\"${escapeHtml(codeChallenge || '')}\">\n <input type=\"hidden\" name=\"codeChallengeMethod\" value=\"${escapeHtml(codeChallengeMethod || 'S256')}\">\n \n <div class=\"form-group\">\n <label for=\"orgId\">Organization ID *</label>\n <input type=\"text\" id=\"orgId\" name=\"orgId\" required placeholder=\"e.g., 12345\">\n <p class=\"help-text\">Found in Settings → API integrations</p>\n </div>\n \n <div class=\"form-group\">\n <label for=\"apiToken\">API Token *</label>\n <input type=\"password\" id=\"apiToken\" name=\"apiToken\" required placeholder=\"pk_...\">\n <p class=\"help-text\">Generate at Settings → API integrations → Generate new token</p>\n </div>\n \n <div class=\"form-group\">\n <label for=\"userId\">User ID (optional)</label>\n <input type=\"text\" id=\"userId\" name=\"userId\" placeholder=\"e.g., 67890\">\n <p class=\"help-text\">Required for creating time entries. Found in your profile URL.</p>\n </div>\n \n <button type=\"submit\">Connect to Productive</button>\n </form>\n \n <p class=\"footer\">\n Your credentials are encrypted and sent directly to Claude.<br>\n <a href=\"https://developer.productive.io\" target=\"_blank\">Productive.io API Documentation</a>\n </p>\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Render error page\n */\nfunction renderErrorPage(message: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Error - Productive MCP</title>\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #f3f4f6;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n }\n .container {\n background: white;\n border-radius: 16px;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n padding: 40px;\n text-align: center;\n max-width: 400px;\n }\n h1 {\n color: #dc2626;\n margin-bottom: 16px;\n }\n p {\n color: #6b7280;\n }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>Error</h1>\n <p>${escapeHtml(message)}</p>\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Escape HTML special characters\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#039;');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,uBAAuB,eAAe,UAAmB;CACpE,MAAM,OAAO,MAAM,IAAI,Q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AAY,EAAE,OAAO,WAAW;AACrE;;;;AAKA,SAAS,gBAAgB,QAQd;CACT,MAAM,EAAE,aAAa,OAAO,eAAe,qBAAqB,UAAU;CAE1E,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAuIH,QAAQ,sBAAsB,WAAW,KAAK,EAAE,UAAU,GAAG;;;uDAGZ,WAAW,eAAe,EAAE,EAAE;iDACpC,WAAW,SAAS,EAAE,EAAE;yDAChB,WAAW,iBAAiB,EAAE,EAAE;+DAC1B,WAAW,uBAAuB,MAAM,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BzG;;;;AAKA,SAAS,gBAAgB,SAAyB;CAChD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAoCA,WAAW,OAAO,EAAE;;;;AAI7B;;;;AAKA,SAAS,WAAW,KAAqB;CACvC,OAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B"}
package/dist/schema.d.ts CHANGED
@@ -261,6 +261,37 @@ export declare const ProductiveToolInputSchema: z.ZodObject<{
261
261
  }, z.core.$loose>>>;
262
262
  }, z.core.$strip>;
263
263
  export type ProductiveToolInput = z.infer<typeof ProductiveToolInputSchema>;
264
+ /**
265
+ * Full input schema for the raw api_read tool.
266
+ */
267
+ export declare const ApiReadToolInputSchema: z.ZodObject<{
268
+ path: z.ZodString;
269
+ describe: z.ZodOptional<z.ZodBoolean>;
270
+ filter: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
271
+ include: z.ZodOptional<z.ZodArray<z.ZodString>>;
272
+ sort: z.ZodOptional<z.ZodArray<z.ZodString>>;
273
+ page: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
274
+ per_page: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
275
+ paginate: z.ZodOptional<z.ZodBoolean>;
276
+ max_pages: z.ZodOptional<z.ZodNumber>;
277
+ }, z.core.$strip>;
278
+ export type ApiReadToolInput = z.infer<typeof ApiReadToolInputSchema>;
279
+ /**
280
+ * Full input schema for the raw api_write tool.
281
+ */
282
+ export declare const ApiWriteToolInputSchema: z.ZodObject<{
283
+ method: z.ZodEnum<{
284
+ DELETE: "DELETE";
285
+ PATCH: "PATCH";
286
+ POST: "POST";
287
+ PUT: "PUT";
288
+ }>;
289
+ path: z.ZodString;
290
+ body: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
291
+ confirm: z.ZodLiteral<true>;
292
+ dry_run: z.ZodOptional<z.ZodBoolean>;
293
+ }, z.core.$strip>;
294
+ export type ApiWriteToolInput = z.infer<typeof ApiWriteToolInputSchema>;
264
295
  /**
265
296
  * Validate and parse tool input
266
297
  * Returns parsed data or throws with validation errors
@@ -274,5 +305,5 @@ export declare function safeValidateToolInput(input: unknown): ZodSafeParseResul
274
305
  /**
275
306
  * Format Zod validation errors for LLM consumption
276
307
  */
277
- export declare function formatValidationErrors(error: ZodError<ProductiveToolInput>): string;
308
+ export declare function formatValidationErrors(error: ZodError<ProductiveToolInput | ApiReadToolInput | ApiWriteToolInput>): string;
278
309
  //# sourceMappingURL=schema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,CAAC,EAAoB,KAAK,kBAAkB,EAAE,KAAK,QAAQ,EAAE,MAAM,KAAK,CAAC;AAGlF,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAMhF;;;GAGG;AACH,eAAO,MAAM,cAAc;;;;;;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M,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAMxE;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,mBAAmB,CAErE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CAAC,mBAAmB,CAAC,CAE7F;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,QAAQ,CAAC,mBAAmB,GAAG,gBAAgB,GAAG,iBAAiB,CAAC,GAC1E,MAAM,CAOR"}
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as VERSION } from "./version-Cy8UEAT1.js";
3
- import { t as createHttpApp } from "./http-CVE4qtko.js";
2
+ import { t as VERSION } from "./version-DMEaGciu.js";
3
+ import { t as createHttpApp } from "./http-QQVUnV2e.js";
4
4
  import { toNodeHandler } from "h3";
5
5
  import { createServer } from "node:http";
6
6
  //#region src/server.ts
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Productive MCP Server - HTTP Transport\n *\n * This is the remote HTTP server mode for Claude Desktop custom connectors.\n * Credentials are passed via Bearer token in the Authorization header.\n *\n * Token format: base64(organizationId:apiToken) or base64(organizationId:apiToken:userId)\n *\n * Generate your token:\n * echo -n \"YOUR_ORG_ID:YOUR_API_TOKEN:YOUR_USER_ID\" | base64\n *\n * Usage:\n * productive-mcp-server\n * PORT=3000 productive-mcp-server\n *\n * Claude Desktop custom connector config:\n * Name: Productive\n * URL: https://productive.mcp.ikko.dev\n * (No OAuth needed - uses Bearer token)\n */\n\nimport { toNodeHandler } from 'h3';\nimport { createServer, type Server } from 'node:http';\n\nimport { createHttpApp } from './http.js';\nimport { VERSION } from './version.js';\n\nconst DEFAULT_PORT = 3000;\nconst DEFAULT_HOST = '0.0.0.0';\n\n/**\n * Start the HTTP server\n */\nexport function startHttpServer(\n port: number = DEFAULT_PORT,\n host: string = DEFAULT_HOST,\n): Promise<Server> {\n return new Promise((resolve) => {\n const app = createHttpApp();\n const server = createServer(toNodeHandler(app));\n\n server.listen(port, host, () => {\n const displayHost = host === '0.0.0.0' ? 'localhost' : host;\n console.log(`Productive MCP server v${VERSION}`);\n console.log(`Node.js ${process.version}`);\n console.log('');\n console.log(`Running at http://${displayHost}:${port}`);\n console.log('');\n console.log('Endpoints:');\n console.log(` POST http://${displayHost}:${port}/mcp - MCP JSON-RPC endpoint`);\n console.log(` GET http://${displayHost}:${port}/health - Health check`);\n console.log('');\n console.log('OAuth 2.0 (MCP auth spec compliant):');\n console.log(` GET http://${displayHost}:${port}/.well-known/oauth-authorization-server`);\n console.log(` POST http://${displayHost}:${port}/register - Dynamic Client Registration`);\n console.log(` GET http://${displayHost}:${port}/authorize - Authorization endpoint`);\n console.log(` POST http://${displayHost}:${port}/token - Token endpoint`);\n console.log('');\n console.log('Authentication:');\n console.log(' Option 1: OAuth flow (Claude Desktop will handle this automatically)');\n console.log(' Option 2: Bearer token in Authorization header');\n console.log(' Token format: base64(organizationId:apiToken:userId)');\n console.log('');\n if (!process.env.OAUTH_SECRET) {\n console.log('⚠️ WARNING: OAUTH_SECRET not set. Set it in production!');\n console.log(' export OAUTH_SECRET=\"your-random-secret-here\"');\n console.log('');\n }\n resolve(server);\n });\n });\n}\n\n// Start server when run directly\nconst isMainModule =\n import.meta.url === `file://${process.argv[1]}` ||\n process.argv[1]?.endsWith('/productive-mcp-server') ||\n process.argv[1]?.endsWith('\\\\productive-mcp-server');\n\nif (isMainModule) {\n const port = Number.parseInt(process.env.PORT || String(DEFAULT_PORT), 10);\n const host = process.env.HOST || DEFAULT_HOST;\n\n startHttpServer(port, host).catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,eAAe;AACrB,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iBAHa,OAAO,SAAS,QAAQ,IAAI,QAAQ,OAAO,aAAa,EAAE,GAAG,EAC7D,QAAQ,IAAI,QAAQ,aAEN,CAAC,OAAO,UAAU;AAC3C,SAAQ,MAAM,gBAAgB,MAAM;AACpC,SAAQ,KAAK,EAAE;EACf"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Productive MCP Server - HTTP Transport\n *\n * This is the remote HTTP server mode for Claude Desktop custom connectors.\n * Credentials are passed via Bearer token in the Authorization header.\n *\n * Token format: base64(organizationId:apiToken) or base64(organizationId:apiToken:userId)\n *\n * Generate your token:\n * echo -n \"YOUR_ORG_ID:YOUR_API_TOKEN:YOUR_USER_ID\" | base64\n *\n * Usage:\n * productive-mcp-server\n * PORT=3000 productive-mcp-server\n *\n * Claude Desktop custom connector config:\n * Name: Productive\n * URL: https://productive.mcp.ikko.dev\n * (No OAuth needed - uses Bearer token)\n */\n\nimport { toNodeHandler } from 'h3';\nimport { createServer, type Server } from 'node:http';\n\nimport { createHttpApp } from './http.js';\nimport { VERSION } from './version.js';\n\nconst DEFAULT_PORT = 3000;\nconst DEFAULT_HOST = '0.0.0.0';\n\n/**\n * Start the HTTP server\n */\nexport function startHttpServer(\n port: number = DEFAULT_PORT,\n host: string = DEFAULT_HOST,\n): Promise<Server> {\n return new Promise((resolve) => {\n const app = createHttpApp();\n const server = createServer(toNodeHandler(app));\n\n server.listen(port, host, () => {\n const displayHost = host === '0.0.0.0' ? 'localhost' : host;\n console.log(`Productive MCP server v${VERSION}`);\n console.log(`Node.js ${process.version}`);\n console.log('');\n console.log(`Running at http://${displayHost}:${port}`);\n console.log('');\n console.log('Endpoints:');\n console.log(` POST http://${displayHost}:${port}/mcp - MCP JSON-RPC endpoint`);\n console.log(` GET http://${displayHost}:${port}/health - Health check`);\n console.log('');\n console.log('OAuth 2.0 (MCP auth spec compliant):');\n console.log(` GET http://${displayHost}:${port}/.well-known/oauth-authorization-server`);\n console.log(` POST http://${displayHost}:${port}/register - Dynamic Client Registration`);\n console.log(` GET http://${displayHost}:${port}/authorize - Authorization endpoint`);\n console.log(` POST http://${displayHost}:${port}/token - Token endpoint`);\n console.log('');\n console.log('Authentication:');\n console.log(' Option 1: OAuth flow (Claude Desktop will handle this automatically)');\n console.log(' Option 2: Bearer token in Authorization header');\n console.log(' Token format: base64(organizationId:apiToken:userId)');\n console.log('');\n if (!process.env.OAUTH_SECRET) {\n console.log('⚠️ WARNING: OAUTH_SECRET not set. Set it in production!');\n console.log(' export OAUTH_SECRET=\"your-random-secret-here\"');\n console.log('');\n }\n resolve(server);\n });\n });\n}\n\n// Start server when run directly\nconst isMainModule =\n import.meta.url === `file://${process.argv[1]}` ||\n process.argv[1]?.endsWith('/productive-mcp-server') ||\n process.argv[1]?.endsWith('\\\\productive-mcp-server');\n\nif (isMainModule) {\n const port = Number.parseInt(process.env.PORT || String(DEFAULT_PORT), 10);\n const host = process.env.HOST || DEFAULT_HOST;\n\n startHttpServer(port, host).catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,eAAe;AACrB,IAAM,eAAe;;;;AAKrB,SAAgB,gBACd,OAAe,cACf,OAAe,cACE;CACjB,OAAO,IAAI,SAAS,YAAY;EAE9B,MAAM,SAAS,aAAa,cADhB,cAC8B,CAAG,CAAC;EAE9C,OAAO,OAAO,MAAM,YAAY;GAC9B,MAAM,cAAc,SAAS,YAAY,cAAc;GACvD,QAAQ,IAAI,0BAA0B,SAAS;GAC/C,QAAQ,IAAI,WAAW,QAAQ,SAAS;GACxC,QAAQ,IAAI,EAAE;GACd,QAAQ,IAAI,qBAAqB,YAAY,GAAG,MAAM;GACtD,QAAQ,IAAI,EAAE;GACd,QAAQ,IAAI,YAAY;GACxB,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,6BAA6B;GAC9E,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,uBAAuB;GACxE,QAAQ,IAAI,EAAE;GACd,QAAQ,IAAI,sCAAsC;GAClD,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,wCAAwC;GACzF,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,wCAAwC;GACzF,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,oCAAoC;GACrF,QAAQ,IAAI,iBAAiB,YAAY,GAAG,KAAK,wBAAwB;GACzE,QAAQ,IAAI,EAAE;GACd,QAAQ,IAAI,iBAAiB;GAC7B,QAAQ,IAAI,wEAAwE;GACpF,QAAQ,IAAI,kDAAkD;GAC9D,QAAQ,IAAI,kEAAkE;GAC9E,QAAQ,IAAI,EAAE;GACd,IAAI,CAAC,QAAQ,IAAI,cAAc;IAC7B,QAAQ,IAAI,0DAA0D;IACtE,QAAQ,IAAI,oDAAkD;IAC9D,QAAQ,IAAI,EAAE;GAChB;GACA,QAAQ,MAAM;EAChB,CAAC;CACH,CAAC;AACH;AAQA,IAJE,OAAO,KAAK,QAAQ,UAAU,QAAQ,KAAK,QAC3C,QAAQ,KAAK,IAAI,SAAS,wBAAwB,KAClD,QAAQ,KAAK,IAAI,SAAS,yBAAyB,GAMnD,gBAHa,OAAO,SAAS,QAAQ,IAAI,QAAQ,OAAO,YAAY,GAAG,EAGvD,GAFH,QAAQ,IAAI,QAAQ,YAEP,EAAE,OAAO,UAAU;CAC3C,QAAQ,MAAM,gBAAgB,KAAK;CACnC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1,4 +1,4 @@
1
- import { t as executeToolWithCredentials } from "./handlers-vtRpc-Lx.js";
1
+ import { t as executeToolWithCredentials } from "./handlers-DonE83xo.js";
2
2
  import { STDIO_ONLY_TOOLS, TOOLS } from "./tools.js";
3
3
  import { getConfig, setConfig } from "@studiometa/productive-api";
4
4
  //#region src/prompts/definitions.ts
@@ -354,4 +354,4 @@ async function handlePrompt(name, args) {
354
354
  //#endregion
355
355
  export { handlePrompt as a, handleGetConfigTool as i, getAvailableTools as n, handleSetupPrompt as o, handleConfigureTool as r, handleToolCall as s, getAvailablePrompts as t };
356
356
 
357
- //# sourceMappingURL=stdio-BFK9AcdQ.js.map
357
+ //# sourceMappingURL=stdio-CRD2nJPs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stdio-BFK9AcdQ.js","names":[],"sources":["../src/prompts/definitions.ts","../src/prompts/handlers.ts","../src/stdio.ts"],"sourcesContent":["/**\n * MCP Prompt Template Definitions\n *\n * Prompt templates serve as guided conversation starters that instruct the LLM\n * which productive tool calls to make and how to format the output.\n */\n\nexport interface PromptArgument {\n name: string;\n description: string;\n required: boolean;\n}\n\nexport interface PromptDefinition {\n name: string;\n description: string;\n arguments: PromptArgument[];\n}\n\nexport const PROMPT_DEFINITIONS: PromptDefinition[] = [\n {\n name: 'end-of-day',\n description: 'Compose an end-of-day standup message based on your activity today',\n arguments: [\n {\n name: 'format',\n description: 'Output format: slack, email, or plain (default: plain)',\n required: false,\n },\n ],\n },\n {\n name: 'project-review',\n description: 'Analyze project health and status with budget, tasks, and timeline overview',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n ],\n },\n {\n name: 'plan-sprint',\n description: 'Help prioritize tasks for the next sprint based on open tasks and budget',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n ],\n },\n {\n name: 'weekly-report',\n description: 'Generate a polished weekly progress report',\n arguments: [\n {\n name: 'person',\n description: 'Person email or ID to report on (default: current user)',\n required: false,\n },\n {\n name: 'format',\n description: 'Output format: slack, email, or plain (default: plain)',\n required: false,\n },\n ],\n },\n {\n name: 'invoice-prep',\n description: 'Prepare a billing summary for a project within a date range',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n {\n name: 'from',\n description: 'Start date in YYYY-MM-DD format',\n required: true,\n },\n {\n name: 'to',\n description: 'End date in YYYY-MM-DD format',\n required: true,\n },\n ],\n },\n];\n","/**\n * MCP Prompt Template Handlers\n *\n * Returns messages arrays that instruct the LLM which productive tool calls to\n * make and how to format and present the output to the user.\n */\n\ntype PromptMessage = {\n role: string;\n content: { type: string; text: string };\n};\n\ntype PromptResult = {\n messages: PromptMessage[];\n};\n\n/**\n * Build the end-of-day standup prompt messages\n */\nfunction endOfDay(args?: Record<string, string>): PromptResult {\n const format = args?.format ?? 'plain';\n\n const formatInstruction =\n format === 'slack'\n ? 'Format the output as a Slack message using emoji bullets and bold text with *asterisks*.'\n : format === 'email'\n ? 'Format the output as a professional email with a subject line and proper greeting/closing.'\n : 'Format the output as a plain-text standup message with clear sections.';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please compose my end-of-day standup message.\n\nFirst, call the productive tool to gather today's activity:\n\\`\\`\\`json\n{ \"resource\": \"summaries\", \"action\": \"my_day\" }\n\\`\\`\\`\n\nThen compose a standup message with these sections:\n- **What I did today**: Summarize completed tasks and logged time by project\n- **What I'm working on tomorrow**: Any open/in-progress tasks from today\n- **Blockers**: Note any overdue tasks or items needing attention\n\n${formatInstruction}\n\nKeep it concise — this is for a standup, not a novel.`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the project-review prompt messages\n */\nfunction projectReview(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please analyze the health and status of project ${project ? `\"${project}\"` : '(project not specified)'}.\n\nFetch all project context in one call:\n\\`\\`\\`json\n{ \"resource\": \"projects\", \"action\": \"context\", \"id\": \"${project}\" }\n\\`\\`\\`\n\nAlso check the project's tasks for a fuller picture:\n\\`\\`\\`json\n{ \"resource\": \"tasks\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"status\": 1 }, \"per_page\": 50 }\n\\`\\`\\`\n\nThen provide a structured project health review covering:\n1. **Overview**: Project name, client, current status\n2. **Budget**: Budget used vs total, burn rate, projected overage risk\n3. **Tasks**: Open vs completed task counts, overdue tasks, upcoming deadlines\n4. **Recent activity**: What has been worked on recently\n5. **Health assessment**: Overall RAG status (🟢 On track / 🟡 At risk / 🔴 Critical) with reasoning\n6. **Recommendations**: Concrete next steps or concerns to address`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the plan-sprint prompt messages\n */\nfunction planSprint(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please help me plan the next sprint for project ${project ? `\"${project}\"` : '(project not specified)'}.\n\nFetch all open tasks for the project:\n\\`\\`\\`json\n{ \"resource\": \"tasks\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"status\": 1 }, \"per_page\": 100 }\n\\`\\`\\`\n\nFetch the project's budget services to understand available capacity:\n\\`\\`\\`json\n{ \"resource\": \"services\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\" }, \"per_page\": 50 }\n\\`\\`\\`\n\nThen provide sprint planning recommendations:\n1. **Backlog summary**: Total open tasks, categories/task-lists breakdown\n2. **Priority candidates**: Top tasks to tackle next sprint based on:\n - Due dates and overdue items\n - Task dependencies (if visible)\n - Effort estimates\n3. **Budget check**: Remaining budget per service — flag if any service is near its limit\n4. **Suggested sprint scope**: A realistic list of tasks for a 1-2 week sprint\n5. **Risks**: Tasks that are blocked, unassigned, or missing estimates`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the weekly-report prompt messages\n */\nfunction weeklyReport(args?: Record<string, string>): PromptResult {\n const person = args?.person;\n const format = args?.format ?? 'plain';\n\n const personInstruction = person\n ? `Focus on person \"${person}\". Resolve the person ID if needed using: { \"resource\": \"people\", \"action\": \"resolve\", \"query\": \"${person}\" } first.`\n : 'Focus on the current authenticated user (use the default person from summaries).';\n\n const formatInstruction =\n format === 'slack'\n ? 'Format as a Slack message with emoji bullets, bold project names, and a summary header.'\n : format === 'email'\n ? 'Format as a professional email with subject line, greeting, bulleted highlights per project, and a closing.'\n : 'Format as a clean plain-text weekly report with clear section headers.';\n\n const standupCall = person\n ? `First resolve the person ID, then fetch weekly standup data:\n\\`\\`\\`json\n{ \"resource\": \"people\", \"action\": \"resolve\", \"query\": \"${person}\" }\n\\`\\`\\`\n\\`\\`\\`json\n{ \"resource\": \"workflows\", \"action\": \"weekly_standup\", \"person_id\": \"<resolved_person_id>\" }\n\\`\\`\\``\n : `Fetch weekly standup data:\n\\`\\`\\`json\n{ \"resource\": \"workflows\", \"action\": \"weekly_standup\" }\n\\`\\`\\``;\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please generate a weekly progress report.\n\n${personInstruction}\n\n${standupCall}\n\nThen compose a polished weekly report with:\n1. **This week's accomplishments**: Completed tasks grouped by project\n2. **Time logged**: Hours per project this week, total hours\n3. **In progress**: Tasks still open that were worked on\n4. **Upcoming**: Any tasks with deadlines in the next 7 days\n5. **Highlights**: Notable wins or milestones reached\n\n${formatInstruction}`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the invoice-prep prompt messages\n */\nfunction invoicePrep(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n const from = args?.from ?? '';\n const to = args?.to ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please prepare a billing summary for project ${project ? `\"${project}\"` : '(project not specified)'} from ${from || '(start date not specified)'} to ${to || '(end date not specified)'}.\n\nFetch time entries for the date range:\n\\`\\`\\`json\n{\n \"resource\": \"time\",\n \"action\": \"list\",\n \"filter\": {\n \"project_id\": \"${project}\",\n \"after\": \"${from}\",\n \"before\": \"${to}\"\n },\n \"include\": [\"person\", \"service\"],\n \"per_page\": 200\n}\n\\`\\`\\`\n\nFetch project services/budget lines:\n\\`\\`\\`json\n{ \"resource\": \"services\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\" }, \"per_page\": 50 }\n\\`\\`\\`\n\nFetch the project deal/budget details:\n\\`\\`\\`json\n{ \"resource\": \"deals\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"type\": 2 }, \"per_page\": 10 }\n\\`\\`\\`\n\nThen produce a billing summary:\n1. **Period**: ${from} → ${to}\n2. **Time entries by service**: Hours logged per service/budget line with team member breakdown\n3. **Billable totals**: If rates are available, calculate amounts per service\n4. **Budget consumed**: Planned vs actual hours per service\n5. **Invoice line items**: Suggested line items ready to copy into an invoice\n6. **Notes**: Any unbilled items, write-offs, or adjustments to flag`,\n },\n },\n ],\n };\n}\n\n/**\n * Get messages for a named prompt template\n */\nexport function getPromptMessages(name: string, args?: Record<string, string>): PromptResult {\n switch (name) {\n case 'end-of-day':\n return endOfDay(args);\n case 'project-review':\n return projectReview(args);\n case 'plan-sprint':\n return planSprint(args);\n case 'weekly-report':\n return weeklyReport(args);\n case 'invoice-prep':\n return invoicePrep(args);\n default:\n throw new Error(`Unknown prompt: ${name}`);\n }\n}\n","/**\n * Stdio transport handlers for Productive MCP Server\n *\n * This module contains the handler logic for the stdio transport.\n * The actual server startup is in index.ts.\n */\n\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport { getConfig, setConfig } from '@studiometa/productive-api';\n\nimport { executeToolWithCredentials } from './handlers.js';\nimport { PROMPT_DEFINITIONS, getPromptMessages } from './prompts/index.js';\nimport { TOOLS, STDIO_ONLY_TOOLS } from './tools.js';\n\nexport type ToolResult = CallToolResult;\n\n/**\n * Get all available tools (including stdio-only configuration tools)\n */\nexport function getAvailableTools() {\n return [...TOOLS, ...STDIO_ONLY_TOOLS];\n}\n\n/**\n * Get available prompts\n */\nexport function getAvailablePrompts() {\n return [\n {\n name: 'setup_productive',\n description: 'Interactive setup for Productive.io credentials',\n arguments: [],\n },\n ...PROMPT_DEFINITIONS,\n ];\n}\n\n/**\n * Handle the setup_productive prompt\n */\nexport async function handleSetupPrompt(): Promise<{\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n}> {\n const config = await getConfig();\n const hasConfig = !!(config.organizationId && config.apiToken);\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: hasConfig\n ? 'I have already configured Productive.io credentials. Would you like to update them?'\n : 'I need to configure my Productive.io credentials. Please help me set up:\\n1. Organization ID\\n2. API Token\\n3. User ID (optional)',\n },\n },\n ],\n };\n}\n\n/**\n * Handle the productive_configure tool\n */\nexport async function handleConfigureTool(args: {\n organizationId: string;\n apiToken: string;\n userId?: string;\n}): Promise<ToolResult> {\n const { organizationId, apiToken, userId } = args;\n\n await setConfig('organizationId', organizationId);\n await setConfig('apiToken', apiToken);\n if (userId) {\n await setConfig('userId', userId);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: true,\n message: 'Productive.io credentials configured successfully',\n configured: {\n organizationId,\n userId: userId || 'not set',\n apiToken: '***' + apiToken.slice(-4),\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n}\n\n/**\n * Handle the productive_get_config tool\n */\nexport async function handleGetConfigTool(): Promise<ToolResult> {\n const currentConfig = await getConfig();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n organizationId: currentConfig.organizationId || 'not configured',\n userId: currentConfig.userId || 'not configured',\n apiToken: currentConfig.apiToken\n ? '***' + currentConfig.apiToken.slice(-4)\n : 'not configured',\n configured: !!(currentConfig.organizationId && currentConfig.apiToken),\n },\n null,\n 2,\n ),\n },\n ],\n };\n}\n\n/**\n * Handle a tool call request\n */\nexport async function handleToolCall(\n name: string,\n args: Record<string, unknown>,\n): Promise<ToolResult> {\n // Handle stdio-only configuration tools\n if (name === 'productive_configure') {\n return handleConfigureTool(args as Parameters<typeof handleConfigureTool>[0]);\n }\n\n if (name === 'productive_get_config') {\n return handleGetConfigTool();\n }\n\n // Get config for API tools\n const config = await getConfig();\n if (!config.organizationId || !config.apiToken) {\n return {\n content: [\n {\n type: 'text',\n text: 'Error: Productive.io credentials not configured. Please use the \"productive_configure\" tool to set your credentials, or set PRODUCTIVE_ORG_ID and PRODUCTIVE_API_TOKEN environment variables.',\n },\n ],\n isError: true,\n };\n }\n\n // Execute tool with credentials from config\n return executeToolWithCredentials(name, args, {\n organizationId: config.organizationId,\n apiToken: config.apiToken,\n userId: config.userId,\n });\n}\n\n/**\n * Handle a prompt request\n */\nexport async function handlePrompt(\n name: string,\n args?: Record<string, string>,\n): Promise<{\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n}> {\n if (name === 'setup_productive') {\n return handleSetupPrompt();\n }\n\n return getPromptMessages(name, args);\n}\n"],"mappings":";;;;AAmBA,IAAa,qBAAyC;CACpD;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;GACX,CACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;GACX,CACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;GACX,CACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;GACX,EACD;GACE,MAAM;GACN,aAAa;GACb,UAAU;GACX,CACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,WAAW;GACT;IACE,MAAM;IACN,aAAa;IACb,UAAU;IACX;GACD;IACE,MAAM;IACN,aAAa;IACb,UAAU;IACX;GACD;IACE,MAAM;IACN,aAAa;IACb,UAAU;IACX;GACF;EACF;CACF;;;;;;ACvED,SAAS,SAAS,MAA6C;CAC7D,MAAM,SAAS,MAAM,UAAU;AAS/B,QAAO,EACL,UAAU,CACR;EACE,MAAM;EACN,SAAS;GACP,MAAM;GACN,MAAM;;;;;;;;;;;;EAZZ,WAAW,UACP,6FACA,WAAW,UACT,+FACA,yEAoBU;;;GAGX;EACF,CACF,EACF;;;;;AAMH,SAAS,cAAc,MAA6C;CAClE,MAAM,UAAU,MAAM,WAAW;AAEjC,QAAO,EACL,UAAU,CACR;EACE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;GACJ,YAAY,CAAC,EAAE,cAAc,kBAAkB,cAAc;GAC9D,EACD,MACA,EACD;EACF,CACF,EACF;;;;;AAMH,eAAsB,eACpB,MACA,MACqB;AAErB,KAAI,SAAS,uBACX,QAAO,oBAAoB,KAAkD;AAG/E,KAAI,SAAS,wBACX,QAAO,qBAAqB;CAI9B,MAAM,SAAS,MAAM,WAAW;AAChC,KAAI,CAAC,OAAO,kBAAkB,CAAC,OAAO,SACpC,QAAO;EACL,SAAS,CACP;GACE,MAAM;GACN,MAAM;GACP,CACF;EACD,SAAS;EACV;AAIH,QAAO,2BAA2B,MAAM,MAAM;EAC5C,gBAAgB,OAAO;EACvB,UAAU,OAAO;EACjB,QAAQ,OAAO;EAChB,CAAC;;;;;AAMJ,eAAsB,aACpB,MACA,MAGC;AACD,KAAI,SAAS,mBACX,QAAO,mBAAmB;AAG5B,QAAO,kBAAkB,MAAM,KAAK"}
1
+ {"version":3,"file":"stdio-CRD2nJPs.js","names":[],"sources":["../src/prompts/definitions.ts","../src/prompts/handlers.ts","../src/stdio.ts"],"sourcesContent":["/**\n * MCP Prompt Template Definitions\n *\n * Prompt templates serve as guided conversation starters that instruct the LLM\n * which productive tool calls to make and how to format the output.\n */\n\nexport interface PromptArgument {\n name: string;\n description: string;\n required: boolean;\n}\n\nexport interface PromptDefinition {\n name: string;\n description: string;\n arguments: PromptArgument[];\n}\n\nexport const PROMPT_DEFINITIONS: PromptDefinition[] = [\n {\n name: 'end-of-day',\n description: 'Compose an end-of-day standup message based on your activity today',\n arguments: [\n {\n name: 'format',\n description: 'Output format: slack, email, or plain (default: plain)',\n required: false,\n },\n ],\n },\n {\n name: 'project-review',\n description: 'Analyze project health and status with budget, tasks, and timeline overview',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n ],\n },\n {\n name: 'plan-sprint',\n description: 'Help prioritize tasks for the next sprint based on open tasks and budget',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n ],\n },\n {\n name: 'weekly-report',\n description: 'Generate a polished weekly progress report',\n arguments: [\n {\n name: 'person',\n description: 'Person email or ID to report on (default: current user)',\n required: false,\n },\n {\n name: 'format',\n description: 'Output format: slack, email, or plain (default: plain)',\n required: false,\n },\n ],\n },\n {\n name: 'invoice-prep',\n description: 'Prepare a billing summary for a project within a date range',\n arguments: [\n {\n name: 'project',\n description: 'Project ID or project number (e.g. PRJ-123)',\n required: true,\n },\n {\n name: 'from',\n description: 'Start date in YYYY-MM-DD format',\n required: true,\n },\n {\n name: 'to',\n description: 'End date in YYYY-MM-DD format',\n required: true,\n },\n ],\n },\n];\n","/**\n * MCP Prompt Template Handlers\n *\n * Returns messages arrays that instruct the LLM which productive tool calls to\n * make and how to format and present the output to the user.\n */\n\ntype PromptMessage = {\n role: string;\n content: { type: string; text: string };\n};\n\ntype PromptResult = {\n messages: PromptMessage[];\n};\n\n/**\n * Build the end-of-day standup prompt messages\n */\nfunction endOfDay(args?: Record<string, string>): PromptResult {\n const format = args?.format ?? 'plain';\n\n const formatInstruction =\n format === 'slack'\n ? 'Format the output as a Slack message using emoji bullets and bold text with *asterisks*.'\n : format === 'email'\n ? 'Format the output as a professional email with a subject line and proper greeting/closing.'\n : 'Format the output as a plain-text standup message with clear sections.';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please compose my end-of-day standup message.\n\nFirst, call the productive tool to gather today's activity:\n\\`\\`\\`json\n{ \"resource\": \"summaries\", \"action\": \"my_day\" }\n\\`\\`\\`\n\nThen compose a standup message with these sections:\n- **What I did today**: Summarize completed tasks and logged time by project\n- **What I'm working on tomorrow**: Any open/in-progress tasks from today\n- **Blockers**: Note any overdue tasks or items needing attention\n\n${formatInstruction}\n\nKeep it concise — this is for a standup, not a novel.`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the project-review prompt messages\n */\nfunction projectReview(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please analyze the health and status of project ${project ? `\"${project}\"` : '(project not specified)'}.\n\nFetch all project context in one call:\n\\`\\`\\`json\n{ \"resource\": \"projects\", \"action\": \"context\", \"id\": \"${project}\" }\n\\`\\`\\`\n\nAlso check the project's tasks for a fuller picture:\n\\`\\`\\`json\n{ \"resource\": \"tasks\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"status\": 1 }, \"per_page\": 50 }\n\\`\\`\\`\n\nThen provide a structured project health review covering:\n1. **Overview**: Project name, client, current status\n2. **Budget**: Budget used vs total, burn rate, projected overage risk\n3. **Tasks**: Open vs completed task counts, overdue tasks, upcoming deadlines\n4. **Recent activity**: What has been worked on recently\n5. **Health assessment**: Overall RAG status (🟢 On track / 🟡 At risk / 🔴 Critical) with reasoning\n6. **Recommendations**: Concrete next steps or concerns to address`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the plan-sprint prompt messages\n */\nfunction planSprint(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please help me plan the next sprint for project ${project ? `\"${project}\"` : '(project not specified)'}.\n\nFetch all open tasks for the project:\n\\`\\`\\`json\n{ \"resource\": \"tasks\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"status\": 1 }, \"per_page\": 100 }\n\\`\\`\\`\n\nFetch the project's budget services to understand available capacity:\n\\`\\`\\`json\n{ \"resource\": \"services\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\" }, \"per_page\": 50 }\n\\`\\`\\`\n\nThen provide sprint planning recommendations:\n1. **Backlog summary**: Total open tasks, categories/task-lists breakdown\n2. **Priority candidates**: Top tasks to tackle next sprint based on:\n - Due dates and overdue items\n - Task dependencies (if visible)\n - Effort estimates\n3. **Budget check**: Remaining budget per service — flag if any service is near its limit\n4. **Suggested sprint scope**: A realistic list of tasks for a 1-2 week sprint\n5. **Risks**: Tasks that are blocked, unassigned, or missing estimates`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the weekly-report prompt messages\n */\nfunction weeklyReport(args?: Record<string, string>): PromptResult {\n const person = args?.person;\n const format = args?.format ?? 'plain';\n\n const personInstruction = person\n ? `Focus on person \"${person}\". Resolve the person ID if needed using: { \"resource\": \"people\", \"action\": \"resolve\", \"query\": \"${person}\" } first.`\n : 'Focus on the current authenticated user (use the default person from summaries).';\n\n const formatInstruction =\n format === 'slack'\n ? 'Format as a Slack message with emoji bullets, bold project names, and a summary header.'\n : format === 'email'\n ? 'Format as a professional email with subject line, greeting, bulleted highlights per project, and a closing.'\n : 'Format as a clean plain-text weekly report with clear section headers.';\n\n const standupCall = person\n ? `First resolve the person ID, then fetch weekly standup data:\n\\`\\`\\`json\n{ \"resource\": \"people\", \"action\": \"resolve\", \"query\": \"${person}\" }\n\\`\\`\\`\n\\`\\`\\`json\n{ \"resource\": \"workflows\", \"action\": \"weekly_standup\", \"person_id\": \"<resolved_person_id>\" }\n\\`\\`\\``\n : `Fetch weekly standup data:\n\\`\\`\\`json\n{ \"resource\": \"workflows\", \"action\": \"weekly_standup\" }\n\\`\\`\\``;\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please generate a weekly progress report.\n\n${personInstruction}\n\n${standupCall}\n\nThen compose a polished weekly report with:\n1. **This week's accomplishments**: Completed tasks grouped by project\n2. **Time logged**: Hours per project this week, total hours\n3. **In progress**: Tasks still open that were worked on\n4. **Upcoming**: Any tasks with deadlines in the next 7 days\n5. **Highlights**: Notable wins or milestones reached\n\n${formatInstruction}`,\n },\n },\n ],\n };\n}\n\n/**\n * Build the invoice-prep prompt messages\n */\nfunction invoicePrep(args?: Record<string, string>): PromptResult {\n const project = args?.project ?? '';\n const from = args?.from ?? '';\n const to = args?.to ?? '';\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Please prepare a billing summary for project ${project ? `\"${project}\"` : '(project not specified)'} from ${from || '(start date not specified)'} to ${to || '(end date not specified)'}.\n\nFetch time entries for the date range:\n\\`\\`\\`json\n{\n \"resource\": \"time\",\n \"action\": \"list\",\n \"filter\": {\n \"project_id\": \"${project}\",\n \"after\": \"${from}\",\n \"before\": \"${to}\"\n },\n \"include\": [\"person\", \"service\"],\n \"per_page\": 200\n}\n\\`\\`\\`\n\nFetch project services/budget lines:\n\\`\\`\\`json\n{ \"resource\": \"services\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\" }, \"per_page\": 50 }\n\\`\\`\\`\n\nFetch the project deal/budget details:\n\\`\\`\\`json\n{ \"resource\": \"deals\", \"action\": \"list\", \"filter\": { \"project_id\": \"${project}\", \"type\": 2 }, \"per_page\": 10 }\n\\`\\`\\`\n\nThen produce a billing summary:\n1. **Period**: ${from} → ${to}\n2. **Time entries by service**: Hours logged per service/budget line with team member breakdown\n3. **Billable totals**: If rates are available, calculate amounts per service\n4. **Budget consumed**: Planned vs actual hours per service\n5. **Invoice line items**: Suggested line items ready to copy into an invoice\n6. **Notes**: Any unbilled items, write-offs, or adjustments to flag`,\n },\n },\n ],\n };\n}\n\n/**\n * Get messages for a named prompt template\n */\nexport function getPromptMessages(name: string, args?: Record<string, string>): PromptResult {\n switch (name) {\n case 'end-of-day':\n return endOfDay(args);\n case 'project-review':\n return projectReview(args);\n case 'plan-sprint':\n return planSprint(args);\n case 'weekly-report':\n return weeklyReport(args);\n case 'invoice-prep':\n return invoicePrep(args);\n default:\n throw new Error(`Unknown prompt: ${name}`);\n }\n}\n","/**\n * Stdio transport handlers for Productive MCP Server\n *\n * This module contains the handler logic for the stdio transport.\n * The actual server startup is in index.ts.\n */\n\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport { getConfig, setConfig } from '@studiometa/productive-api';\n\nimport { executeToolWithCredentials } from './handlers.js';\nimport { PROMPT_DEFINITIONS, getPromptMessages } from './prompts/index.js';\nimport { TOOLS, STDIO_ONLY_TOOLS } from './tools.js';\n\nexport type ToolResult = CallToolResult;\n\n/**\n * Get all available tools (including stdio-only configuration tools)\n */\nexport function getAvailableTools() {\n return [...TOOLS, ...STDIO_ONLY_TOOLS];\n}\n\n/**\n * Get available prompts\n */\nexport function getAvailablePrompts() {\n return [\n {\n name: 'setup_productive',\n description: 'Interactive setup for Productive.io credentials',\n arguments: [],\n },\n ...PROMPT_DEFINITIONS,\n ];\n}\n\n/**\n * Handle the setup_productive prompt\n */\nexport async function handleSetupPrompt(): Promise<{\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n}> {\n const config = await getConfig();\n const hasConfig = !!(config.organizationId && config.apiToken);\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: hasConfig\n ? 'I have already configured Productive.io credentials. Would you like to update them?'\n : 'I need to configure my Productive.io credentials. Please help me set up:\\n1. Organization ID\\n2. API Token\\n3. User ID (optional)',\n },\n },\n ],\n };\n}\n\n/**\n * Handle the productive_configure tool\n */\nexport async function handleConfigureTool(args: {\n organizationId: string;\n apiToken: string;\n userId?: string;\n}): Promise<ToolResult> {\n const { organizationId, apiToken, userId } = args;\n\n await setConfig('organizationId', organizationId);\n await setConfig('apiToken', apiToken);\n if (userId) {\n await setConfig('userId', userId);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: true,\n message: 'Productive.io credentials configured successfully',\n configured: {\n organizationId,\n userId: userId || 'not set',\n apiToken: '***' + apiToken.slice(-4),\n },\n },\n null,\n 2,\n ),\n },\n ],\n };\n}\n\n/**\n * Handle the productive_get_config tool\n */\nexport async function handleGetConfigTool(): Promise<ToolResult> {\n const currentConfig = await getConfig();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n organizationId: currentConfig.organizationId || 'not configured',\n userId: currentConfig.userId || 'not configured',\n apiToken: currentConfig.apiToken\n ? '***' + currentConfig.apiToken.slice(-4)\n : 'not configured',\n configured: !!(currentConfig.organizationId && currentConfig.apiToken),\n },\n null,\n 2,\n ),\n },\n ],\n };\n}\n\n/**\n * Handle a tool call request\n */\nexport async function handleToolCall(\n name: string,\n args: Record<string, unknown>,\n): Promise<ToolResult> {\n // Handle stdio-only configuration tools\n if (name === 'productive_configure') {\n return handleConfigureTool(args as Parameters<typeof handleConfigureTool>[0]);\n }\n\n if (name === 'productive_get_config') {\n return handleGetConfigTool();\n }\n\n // Get config for API tools\n const config = await getConfig();\n if (!config.organizationId || !config.apiToken) {\n return {\n content: [\n {\n type: 'text',\n text: 'Error: Productive.io credentials not configured. Please use the \"productive_configure\" tool to set your credentials, or set PRODUCTIVE_ORG_ID and PRODUCTIVE_API_TOKEN environment variables.',\n },\n ],\n isError: true,\n };\n }\n\n // Execute tool with credentials from config\n return executeToolWithCredentials(name, args, {\n organizationId: config.organizationId,\n apiToken: config.apiToken,\n userId: config.userId,\n });\n}\n\n/**\n * Handle a prompt request\n */\nexport async function handlePrompt(\n name: string,\n args?: Record<string, string>,\n): Promise<{\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n}> {\n if (name === 'setup_productive') {\n return handleSetupPrompt();\n }\n\n return getPromptMessages(name, args);\n}\n"],"mappings":";;;;AAmBA,IAAa,qBAAyC;CACpD;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,WAAW,CACT;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,GACA;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,WAAW;GACT;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IAC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GlC,OAAO,EACL,SAAS,CACP;EACE,MAAM;EACN,MAAM,KAAK,UACT;GACE,SAAS;GACT,SAAS;GACT,YAAY;IACV;IACA,QAAQ,UAAU;IAClB,UAAU,QAAQ,SAAS,MAAM,EAAE;GACrC;EACF,GACA,MACA,CACF;CACF,CACF,EACF;AACF;;;;AAKA,eAAsB,sBAA2C;CAC/D,MAAM,gBAAgB,MAAM,UAAU;CACtC,OAAO,EACL,SAAS,CACP;EACE,MAAM;EACN,MAAM,KAAK,UACT;GACE,gBAAgB,cAAc,kBAAkB;GAChD,QAAQ,cAAc,UAAU;GAChC,UAAU,cAAc,WACpB,QAAQ,cAAc,SAAS,MAAM,EAAE,IACvC;GACJ,YAAY,CAAC,EAAE,cAAc,kBAAkB,cAAc;EAC/D,GACA,MACA,CACF;CACF,CACF,EACF;AACF;;;;AAKA,eAAsB,eACpB,MACA,MACqB;CAErB,IAAI,SAAS,wBACX,OAAO,oBAAoB,IAAiD;CAG9E,IAAI,SAAS,yBACX,OAAO,oBAAoB;CAI7B,MAAM,SAAS,MAAM,UAAU;CAC/B,IAAI,CAAC,OAAO,kBAAkB,CAAC,OAAO,UACpC,OAAO;EACL,SAAS,CACP;GACE,MAAM;GACN,MAAM;EACR,CACF;EACA,SAAS;CACX;CAIF,OAAO,2BAA2B,MAAM,MAAM;EAC5C,gBAAgB,OAAO;EACvB,UAAU,OAAO;EACjB,QAAQ,OAAO;CACjB,CAAC;AACH;;;;AAKA,eAAsB,aACpB,MACA,MAGC;CACD,IAAI,SAAS,oBACX,OAAO,kBAAkB;CAG3B,OAAO,kBAAkB,MAAM,IAAI;AACrC"}
package/dist/stdio.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as handlePrompt, i as handleGetConfigTool, n as getAvailableTools, o as handleSetupPrompt, r as handleConfigureTool, s as handleToolCall, t as getAvailablePrompts } from "./stdio-BFK9AcdQ.js";
1
+ import { a as handlePrompt, i as handleGetConfigTool, n as getAvailableTools, o as handleSetupPrompt, r as handleConfigureTool, s as handleToolCall, t as getAvailablePrompts } from "./stdio-CRD2nJPs.js";
2
2
  export { getAvailablePrompts, getAvailableTools, handleConfigureTool, handleGetConfigTool, handlePrompt, handleSetupPrompt, handleToolCall };
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,oCAAoC,CAAC;AAwB/D;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,EA0GvB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,EAoClC,CAAC"}
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,oCAAoC,CAAC;AAwB/D;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,EA+JvB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,EAoClC,CAAC"}