@forumviriumhelsinki/podio-mcp 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +491 -0
  3. package/build/__tests__/integration/setup.integration.d.ts +104 -0
  4. package/build/__tests__/integration/setup.integration.d.ts.map +1 -0
  5. package/build/__tests__/integration/setup.integration.js +233 -0
  6. package/build/__tests__/integration/setup.integration.js.map +1 -0
  7. package/build/__tests__/mock-data/items-mock-data.d.ts +168 -0
  8. package/build/__tests__/mock-data/items-mock-data.d.ts.map +1 -0
  9. package/build/__tests__/mock-data/items-mock-data.js +370 -0
  10. package/build/__tests__/mock-data/items-mock-data.js.map +1 -0
  11. package/build/__tests__/mock-data/notification-mock-data.d.ts +55 -0
  12. package/build/__tests__/mock-data/notification-mock-data.d.ts.map +1 -0
  13. package/build/__tests__/mock-data/notification-mock-data.js +190 -0
  14. package/build/__tests__/mock-data/notification-mock-data.js.map +1 -0
  15. package/build/__tests__/mock-data/project-epic-mock-data.d.ts +45 -0
  16. package/build/__tests__/mock-data/project-epic-mock-data.d.ts.map +1 -0
  17. package/build/__tests__/mock-data/project-epic-mock-data.js +85 -0
  18. package/build/__tests__/mock-data/project-epic-mock-data.js.map +1 -0
  19. package/build/__tests__/mock-data/tasks-mock-data.d.ts +27 -0
  20. package/build/__tests__/mock-data/tasks-mock-data.d.ts.map +1 -0
  21. package/build/__tests__/mock-data/tasks-mock-data.js +104 -0
  22. package/build/__tests__/mock-data/tasks-mock-data.js.map +1 -0
  23. package/build/__tests__/mock-data/utility-mock-data.d.ts +19 -0
  24. package/build/__tests__/mock-data/utility-mock-data.d.ts.map +1 -0
  25. package/build/__tests__/mock-data/utility-mock-data.js +165 -0
  26. package/build/__tests__/mock-data/utility-mock-data.js.map +1 -0
  27. package/build/__tests__/setup.d.ts +8 -0
  28. package/build/__tests__/setup.d.ts.map +1 -0
  29. package/build/__tests__/setup.js +31 -0
  30. package/build/__tests__/setup.js.map +1 -0
  31. package/build/__tests__/utils/test-helpers.d.ts +110 -0
  32. package/build/__tests__/utils/test-helpers.d.ts.map +1 -0
  33. package/build/__tests__/utils/test-helpers.js +222 -0
  34. package/build/__tests__/utils/test-helpers.js.map +1 -0
  35. package/build/api/podio-api-client.d.ts +364 -0
  36. package/build/api/podio-api-client.d.ts.map +1 -0
  37. package/build/api/podio-api-client.js +696 -0
  38. package/build/api/podio-api-client.js.map +1 -0
  39. package/build/cache/app-cache.d.ts +77 -0
  40. package/build/cache/app-cache.d.ts.map +1 -0
  41. package/build/cache/app-cache.js +230 -0
  42. package/build/cache/app-cache.js.map +1 -0
  43. package/build/cache/base-cache-manager.d.ts +149 -0
  44. package/build/cache/base-cache-manager.d.ts.map +1 -0
  45. package/build/cache/base-cache-manager.js +312 -0
  46. package/build/cache/base-cache-manager.js.map +1 -0
  47. package/build/cache/cache-manager.d.ts +230 -0
  48. package/build/cache/cache-manager.d.ts.map +1 -0
  49. package/build/cache/cache-manager.js +362 -0
  50. package/build/cache/cache-manager.js.map +1 -0
  51. package/build/cache/cache-test.d.ts +9 -0
  52. package/build/cache/cache-test.d.ts.map +1 -0
  53. package/build/cache/cache-test.js +169 -0
  54. package/build/cache/cache-test.js.map +1 -0
  55. package/build/cache/index.d.ts +18 -0
  56. package/build/cache/index.d.ts.map +1 -0
  57. package/build/cache/index.js +20 -0
  58. package/build/cache/index.js.map +1 -0
  59. package/build/cache/migration-helper.d.ts +44 -0
  60. package/build/cache/migration-helper.d.ts.map +1 -0
  61. package/build/cache/migration-helper.js +235 -0
  62. package/build/cache/migration-helper.js.map +1 -0
  63. package/build/cache/project-epic-cache.d.ts +108 -0
  64. package/build/cache/project-epic-cache.d.ts.map +1 -0
  65. package/build/cache/project-epic-cache.js +278 -0
  66. package/build/cache/project-epic-cache.js.map +1 -0
  67. package/build/cache/space-members-cache.d.ts +99 -0
  68. package/build/cache/space-members-cache.d.ts.map +1 -0
  69. package/build/cache/space-members-cache.js +305 -0
  70. package/build/cache/space-members-cache.js.map +1 -0
  71. package/build/cache/storage-adapters.d.ts +100 -0
  72. package/build/cache/storage-adapters.d.ts.map +1 -0
  73. package/build/cache/storage-adapters.js +297 -0
  74. package/build/cache/storage-adapters.js.map +1 -0
  75. package/build/errors/api-errors.d.ts +52 -0
  76. package/build/errors/api-errors.d.ts.map +1 -0
  77. package/build/errors/api-errors.js +86 -0
  78. package/build/errors/api-errors.js.map +1 -0
  79. package/build/errors/auth-errors.d.ts +67 -0
  80. package/build/errors/auth-errors.d.ts.map +1 -0
  81. package/build/errors/auth-errors.js +114 -0
  82. package/build/errors/auth-errors.js.map +1 -0
  83. package/build/errors/base.d.ts +102 -0
  84. package/build/errors/base.d.ts.map +1 -0
  85. package/build/errors/base.js +131 -0
  86. package/build/errors/base.js.map +1 -0
  87. package/build/errors/cache-errors.d.ts +53 -0
  88. package/build/errors/cache-errors.d.ts.map +1 -0
  89. package/build/errors/cache-errors.js +83 -0
  90. package/build/errors/cache-errors.js.map +1 -0
  91. package/build/errors/config-errors.d.ts +58 -0
  92. package/build/errors/config-errors.d.ts.map +1 -0
  93. package/build/errors/config-errors.js +96 -0
  94. package/build/errors/config-errors.js.map +1 -0
  95. package/build/errors/index.d.ts +101 -0
  96. package/build/errors/index.d.ts.map +1 -0
  97. package/build/errors/index.js +135 -0
  98. package/build/errors/index.js.map +1 -0
  99. package/build/errors/structure-errors.d.ts +89 -0
  100. package/build/errors/structure-errors.d.ts.map +1 -0
  101. package/build/errors/structure-errors.js +182 -0
  102. package/build/errors/structure-errors.js.map +1 -0
  103. package/build/errors/validation-errors.d.ts +81 -0
  104. package/build/errors/validation-errors.d.ts.map +1 -0
  105. package/build/errors/validation-errors.js +169 -0
  106. package/build/errors/validation-errors.js.map +1 -0
  107. package/build/fields/field-mapper.d.ts +245 -0
  108. package/build/fields/field-mapper.d.ts.map +1 -0
  109. package/build/fields/field-mapper.js +404 -0
  110. package/build/fields/field-mapper.js.map +1 -0
  111. package/build/index.d.ts +550 -0
  112. package/build/index.d.ts.map +1 -0
  113. package/build/index.js +1527 -0
  114. package/build/index.js.map +1 -0
  115. package/build/oauth-helper.d.ts +189 -0
  116. package/build/oauth-helper.d.ts.map +1 -0
  117. package/build/oauth-helper.js +422 -0
  118. package/build/oauth-helper.js.map +1 -0
  119. package/build/services/app-structure-service.d.ts +49 -0
  120. package/build/services/app-structure-service.d.ts.map +1 -0
  121. package/build/services/app-structure-service.js +122 -0
  122. package/build/services/app-structure-service.js.map +1 -0
  123. package/build/services/code-execution-service.d.ts +88 -0
  124. package/build/services/code-execution-service.d.ts.map +1 -0
  125. package/build/services/code-execution-service.js +342 -0
  126. package/build/services/code-execution-service.js.map +1 -0
  127. package/build/services/comment-service.d.ts +66 -0
  128. package/build/services/comment-service.d.ts.map +1 -0
  129. package/build/services/comment-service.js +139 -0
  130. package/build/services/comment-service.js.map +1 -0
  131. package/build/services/index.d.ts +16 -0
  132. package/build/services/index.d.ts.map +1 -0
  133. package/build/services/index.js +15 -0
  134. package/build/services/index.js.map +1 -0
  135. package/build/services/item-service.d.ts +104 -0
  136. package/build/services/item-service.d.ts.map +1 -0
  137. package/build/services/item-service.js +368 -0
  138. package/build/services/item-service.js.map +1 -0
  139. package/build/services/notification-service.d.ts +125 -0
  140. package/build/services/notification-service.d.ts.map +1 -0
  141. package/build/services/notification-service.js +321 -0
  142. package/build/services/notification-service.js.map +1 -0
  143. package/build/services/project-epic-service.d.ts +73 -0
  144. package/build/services/project-epic-service.d.ts.map +1 -0
  145. package/build/services/project-epic-service.js +248 -0
  146. package/build/services/project-epic-service.js.map +1 -0
  147. package/build/services/response-formatter.d.ts +190 -0
  148. package/build/services/response-formatter.d.ts.map +1 -0
  149. package/build/services/response-formatter.js +1221 -0
  150. package/build/services/response-formatter.js.map +1 -0
  151. package/build/services/search-service.d.ts +103 -0
  152. package/build/services/search-service.d.ts.map +1 -0
  153. package/build/services/search-service.js +273 -0
  154. package/build/services/search-service.js.map +1 -0
  155. package/build/services/task-service.d.ts +70 -0
  156. package/build/services/task-service.d.ts.map +1 -0
  157. package/build/services/task-service.js +156 -0
  158. package/build/services/task-service.js.map +1 -0
  159. package/build/tools/index.d.ts +8 -0
  160. package/build/tools/index.d.ts.map +1 -0
  161. package/build/tools/index.js +8 -0
  162. package/build/tools/index.js.map +1 -0
  163. package/build/tools/tool-definitions.d.ts +89 -0
  164. package/build/tools/tool-definitions.d.ts.map +1 -0
  165. package/build/tools/tool-definitions.js +1167 -0
  166. package/build/tools/tool-definitions.js.map +1 -0
  167. package/build/types/api-types.d.ts +106 -0
  168. package/build/types/api-types.d.ts.map +1 -0
  169. package/build/types/api-types.js +11 -0
  170. package/build/types/api-types.js.map +1 -0
  171. package/build/types/cache-types.d.ts +52 -0
  172. package/build/types/cache-types.d.ts.map +1 -0
  173. package/build/types/cache-types.js +12 -0
  174. package/build/types/cache-types.js.map +1 -0
  175. package/build/types/index.d.ts +31 -0
  176. package/build/types/index.d.ts.map +1 -0
  177. package/build/types/index.js +25 -0
  178. package/build/types/index.js.map +1 -0
  179. package/build/types/notification-types.d.ts +154 -0
  180. package/build/types/notification-types.d.ts.map +1 -0
  181. package/build/types/notification-types.js +7 -0
  182. package/build/types/notification-types.js.map +1 -0
  183. package/build/types/podio-types.d.ts +250 -0
  184. package/build/types/podio-types.d.ts.map +1 -0
  185. package/build/types/podio-types.js +11 -0
  186. package/build/types/podio-types.js.map +1 -0
  187. package/build/types/search-types.d.ts +188 -0
  188. package/build/types/search-types.d.ts.map +1 -0
  189. package/build/types/search-types.js +43 -0
  190. package/build/types/search-types.js.map +1 -0
  191. package/build/utils/debug.d.ts +58 -0
  192. package/build/utils/debug.d.ts.map +1 -0
  193. package/build/utils/debug.js +147 -0
  194. package/build/utils/debug.js.map +1 -0
  195. package/examples/claude-config-example.json +13 -0
  196. package/package.json +87 -0
  197. package/scripts/generate-claude-config.js +107 -0
package/build/index.js ADDED
@@ -0,0 +1,1527 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @fileoverview Podio MCP Server - A Model Context Protocol server for integrating Podio with Claude Desktop.
4
+ *
5
+ * This server provides natural language management of Podio items and tasks through Claude conversations.
6
+ * It implements the MCP protocol to expose Podio operations as tools that can be called by AI assistants.
7
+ *
8
+ * @version 0.2.0 - Refactored with modular architecture
9
+ * @author Podio MCP Team
10
+ */
11
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
12
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js';
14
+ // Core modules
15
+ import { PodioOAuthHelper } from './oauth-helper.js';
16
+ import { PodioApiClient } from './api/podio-api-client.js';
17
+ import { CacheManager } from './cache/cache-manager.js';
18
+ import { toolDefinitions } from './tools/tool-definitions.js';
19
+ // Service layer
20
+ import { ResponseFormatter, ItemService, TaskService, ProjectEpicService, AppStructureService, NotificationService, SearchService, CommentService, CodeExecutionService, } from './services/index.js';
21
+ import { PodioErrorCode, PodioConfigError, PodioStructureError, PodioValidationError, isPodioError, PodioErrorFactory, } from './errors/index.js';
22
+ /**
23
+ * Refactored MCP server class that coordinates modular components.
24
+ *
25
+ * This class now serves as a lightweight coordinator between the MCP protocol
26
+ * and specialized service classes. It delegates API calls, caching, field operations,
27
+ * and error handling to dedicated modules for better maintainability.
28
+ *
29
+ * The server uses dependency injection and modular architecture for improved
30
+ * testability and separation of concerns.
31
+ *
32
+ * @class PodioMCPServer
33
+ * @example
34
+ * ```typescript
35
+ * const server = new PodioMCPServer();
36
+ * await server.run();
37
+ * ```
38
+ */
39
+ class PodioMCPServer {
40
+ /** The underlying MCP server instance */
41
+ server;
42
+ /** OAuth helper for managing authentication */
43
+ oauthHelper = null;
44
+ /** API client for all Podio operations */
45
+ apiClient = null;
46
+ /** Unified cache manager */
47
+ cacheManager;
48
+ /** Map of loaded app structures with field mappers by coordinates key */
49
+ loadedApps = new Map();
50
+ /** Default/active app coordinates for backward compatibility */
51
+ activeAppKey = null;
52
+ /** Service layer instances */
53
+ itemService = null;
54
+ taskService = null;
55
+ projectEpicService = null;
56
+ appStructureService = null;
57
+ notificationService = null;
58
+ searchService = null;
59
+ commentService = null;
60
+ codeExecutionService = null;
61
+ /**
62
+ * Initialize the refactored Podio MCP server.
63
+ *
64
+ * Sets up the MCP server with modular components and initializes
65
+ * OAuth authentication and API client if credentials are available.
66
+ *
67
+ * Required environment variables:
68
+ * - PODIO_CLIENT_ID: Your Podio app's client ID
69
+ * - PODIO_CLIENT_SECRET: Your Podio app's client secret
70
+ * - PODIO_REDIRECT_URI: OAuth redirect URI (typically http://localhost:8080/callback)
71
+ *
72
+ * @constructor
73
+ */
74
+ constructor() {
75
+ this.server = new Server({
76
+ name: 'podio-mcp',
77
+ version: '0.2.0',
78
+ capabilities: {
79
+ tools: {},
80
+ },
81
+ });
82
+ // Initialize cache manager
83
+ this.cacheManager = new CacheManager({
84
+ enableLogging: true,
85
+ });
86
+ this.setupToolHandlers();
87
+ this.initializeAuthAndApi();
88
+ }
89
+ /**
90
+ * Initialize OAuth helper and API client from environment variables.
91
+ *
92
+ * @private
93
+ */
94
+ initializeAuthAndApi() {
95
+ const clientId = process.env.PODIO_CLIENT_ID;
96
+ const clientSecret = process.env.PODIO_CLIENT_SECRET;
97
+ const redirectUri = process.env.PODIO_REDIRECT_URI;
98
+ if (!clientId || !clientSecret || !redirectUri) {
99
+ console.error('WARNING: OAuth credentials not found in environment variables. Some functionality may be limited.');
100
+ return;
101
+ }
102
+ try {
103
+ this.oauthHelper = new PodioOAuthHelper(clientId, clientSecret, redirectUri);
104
+ this.apiClient = new PodioApiClient(this.oauthHelper);
105
+ // Initialize service layer
106
+ this.itemService = new ItemService(this.apiClient, this.cacheManager);
107
+ this.taskService = new TaskService(this.apiClient, this.cacheManager);
108
+ this.projectEpicService = new ProjectEpicService(this.apiClient, this.cacheManager);
109
+ this.appStructureService = new AppStructureService(this.apiClient, this.cacheManager);
110
+ this.notificationService = new NotificationService(this.apiClient, this.cacheManager);
111
+ this.searchService = new SearchService(this.apiClient, this.cacheManager);
112
+ this.commentService = new CommentService(this.apiClient, this.cacheManager);
113
+ this.codeExecutionService = new CodeExecutionService(this.apiClient, this.cacheManager);
114
+ console.error('✅ OAuth, API client, and services initialized successfully');
115
+ }
116
+ catch (error) {
117
+ console.error('❌ Failed to initialize OAuth/API client:', error);
118
+ throw PodioConfigError.invalidCredentials('Failed to initialize OAuth helper', error instanceof Error ? error : undefined);
119
+ }
120
+ }
121
+ /**
122
+ * Set up MCP request handlers for tools.
123
+ *
124
+ * Uses the modular tool definitions and proper error handling.
125
+ *
126
+ * @private
127
+ */
128
+ setupToolHandlers() {
129
+ // List available tools
130
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => {
131
+ return {
132
+ tools: toolDefinitions.getAllTools(),
133
+ };
134
+ });
135
+ // Handle tool calls with comprehensive error handling
136
+ this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
137
+ const { name, arguments: args } = request.params;
138
+ try {
139
+ // Validate tool exists
140
+ const tool = toolDefinitions.getToolByName(name);
141
+ if (!tool) {
142
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
143
+ }
144
+ // Validate input schema
145
+ const validation = toolDefinitions.validateToolSchema(name, args);
146
+ if (!validation.valid) {
147
+ throw new McpError(ErrorCode.InvalidParams, `Invalid parameters for tool ${name}: ${validation.errors.join(', ')}`);
148
+ }
149
+ // Route to appropriate handler
150
+ return await this.handleToolCall(name, args);
151
+ }
152
+ catch (error) {
153
+ return this.handleToolError(name, error);
154
+ }
155
+ });
156
+ }
157
+ /**
158
+ * Route tool calls to appropriate handlers.
159
+ *
160
+ * @private
161
+ * @param name - Tool name
162
+ * @param args - Tool arguments
163
+ * @returns Tool response
164
+ */
165
+ async handleToolCall(name, args) {
166
+ switch (name) {
167
+ // App Management
168
+ case 'get_app_structure':
169
+ return await this.getAppStructure(args);
170
+ case 'cache_app_structure':
171
+ return await this.cacheAppStructure(args);
172
+ case 'list_cached_apps':
173
+ return await this.listCachedApps();
174
+ case 'refresh_app_cache':
175
+ return await this.refreshAppCache(args);
176
+ case 'clear_app_cache':
177
+ return await this.clearAppCache(args);
178
+ case 'set_active_app':
179
+ return await this.setActiveApp(args);
180
+ // Item Operations
181
+ case 'list_items':
182
+ return await this.listItems(args);
183
+ case 'create_item':
184
+ return await this.createItem(args);
185
+ case 'update_item':
186
+ return await this.updateItem(args);
187
+ case 'delete_item':
188
+ return await this.deleteItem(args);
189
+ case 'get_item_details':
190
+ return await this.getItemDetails(args);
191
+ case 'get_item_by_app_item_id':
192
+ return await this.getItemByAppItemId(args);
193
+ case 'update_item_by_app_item_id':
194
+ return await this.updateItemByAppItemId(args);
195
+ case 'delete_item_by_app_item_id':
196
+ return await this.deleteItemByAppItemId(args);
197
+ // Task Management
198
+ case 'list_tasks':
199
+ return await this.listTasks(args);
200
+ case 'create_task':
201
+ return await this.createTask(args);
202
+ case 'create_task_for_item':
203
+ return await this.createTaskForItem(args);
204
+ case 'update_task':
205
+ return await this.updateTask(args);
206
+ case 'delete_task':
207
+ return await this.deleteTask(args);
208
+ case 'get_task_details':
209
+ return await this.getTaskDetails(args);
210
+ // Project/Epic Management
211
+ case 'list_projects':
212
+ return await this.listProjects(args);
213
+ case 'list_epics':
214
+ return await this.listEpics(args);
215
+ case 'suggest_project_epic':
216
+ return await this.suggestProjectEpic(args);
217
+ // Notification Management
218
+ case 'list_notifications':
219
+ return await this.listNotifications(args);
220
+ case 'get_notification_details':
221
+ return await this.getNotificationDetails(args);
222
+ case 'get_unread_count':
223
+ return await this.getUnreadCount(args);
224
+ case 'get_notification_settings':
225
+ return await this.getNotificationSettings(args);
226
+ // Search Operations
227
+ case 'search_podio':
228
+ return await this.searchPodio(args);
229
+ case 'search_in_app':
230
+ return await this.searchInApp(args);
231
+ case 'search_in_space':
232
+ return await this.searchInSpace(args);
233
+ case 'get_search_history':
234
+ return await this.getSearchHistory(args);
235
+ case 'clear_search_history':
236
+ return await this.clearSearchHistory(args);
237
+ // Comment & Activity Operations
238
+ case 'list_item_comments':
239
+ return await this.listItemComments(args);
240
+ case 'create_item_comment':
241
+ return await this.createItemComment(args);
242
+ case 'get_comment_details':
243
+ return await this.getCommentDetails(args);
244
+ case 'update_comment':
245
+ return await this.updateComment(args);
246
+ case 'delete_comment':
247
+ return await this.deleteComment(args);
248
+ case 'list_item_activity':
249
+ return await this.listItemActivity(args);
250
+ case 'get_item_revision':
251
+ return await this.getItemRevision(args);
252
+ case 'get_item_revision_diff':
253
+ return await this.getItemRevisionDiff(args);
254
+ // Utility Tools
255
+ case 'inspect_field_structure':
256
+ return await this.inspectFieldStructure(args);
257
+ case 'list_space_members':
258
+ return await this.listSpaceMembers(args);
259
+ // Code Execution
260
+ case 'execute_code':
261
+ return await this.executeCode(args);
262
+ case 'list_code_functions':
263
+ return await this.listCodeFunctions();
264
+ default:
265
+ throw new McpError(ErrorCode.MethodNotFound, `Handler not implemented for tool: ${name}`);
266
+ }
267
+ }
268
+ /**
269
+ * Handle errors from tool execution with proper typing.
270
+ *
271
+ * @private
272
+ * @param toolName - Name of the tool that failed
273
+ * @param error - The error that occurred
274
+ * @returns Formatted error response
275
+ */
276
+ handleToolError(toolName, error) {
277
+ // Handle Podio-specific errors
278
+ if (isPodioError(error)) {
279
+ throw new McpError(ErrorCode.InternalError, `Podio ${error.name}: ${error.message}`);
280
+ }
281
+ // Handle MCP errors (re-throw as-is)
282
+ if (error instanceof McpError) {
283
+ throw error;
284
+ }
285
+ // Handle generic errors
286
+ const message = error instanceof Error ? error.message : String(error);
287
+ throw new McpError(ErrorCode.InternalError, `Tool ${toolName} failed: ${message}`);
288
+ }
289
+ /**
290
+ * Ensure API client and services are available and authenticated.
291
+ *
292
+ * @private
293
+ * @throws PodioAuthError if authentication is not available
294
+ */
295
+ ensureServicesAvailable() {
296
+ if (!this.apiClient ||
297
+ !this.itemService ||
298
+ !this.taskService ||
299
+ !this.projectEpicService ||
300
+ !this.appStructureService ||
301
+ !this.notificationService ||
302
+ !this.searchService ||
303
+ !this.commentService) {
304
+ throw PodioErrorFactory.authNotInitialized([
305
+ 'PODIO_CLIENT_ID',
306
+ 'PODIO_CLIENT_SECRET',
307
+ 'PODIO_REDIRECT_URI',
308
+ ]);
309
+ }
310
+ }
311
+ /**
312
+ * Get the coordinate key for a given set of coordinates.
313
+ *
314
+ * @private
315
+ * @param coordinates - App coordinates
316
+ * @returns String key for the coordinates
317
+ */
318
+ getCoordinateKey(coordinates) {
319
+ return `${coordinates.org_label}:${coordinates.space_label}:${coordinates.app_label}`;
320
+ }
321
+ /**
322
+ * Get the active app structure and field mapper.
323
+ *
324
+ * @private
325
+ * @returns Active app structure and field mapper or null
326
+ */
327
+ getActiveApp() {
328
+ if (!this.activeAppKey)
329
+ return null;
330
+ return this.loadedApps.get(this.activeAppKey) || null;
331
+ }
332
+ /**
333
+ * Get app context for an operation - either from provided coordinates or active app.
334
+ * Throws a helpful error if no app context is available.
335
+ *
336
+ * @private
337
+ * @param args - Arguments potentially containing coordinates
338
+ * @param operation - Operation name for error message
339
+ * @returns App context with structure and field mapper
340
+ */
341
+ async getAppContextForOperation(args, operation) {
342
+ const { org_label, space_label, app_label } = args;
343
+ this.ensureServicesAvailable();
344
+ let appContext = null;
345
+ // If coordinates provided, ensure that app is loaded
346
+ if (org_label && space_label && app_label) {
347
+ appContext = await this.ensureAppStructureLoaded({ org_label, space_label, app_label });
348
+ }
349
+ else {
350
+ // Use active app context
351
+ appContext = this.getActiveApp();
352
+ }
353
+ if (!appContext) {
354
+ // Provide a helpful error message that prompts for coordinates
355
+ const message = `No Podio app is currently active. To ${operation}, either:\n` +
356
+ '1. Provide workspace coordinates in your request:\n' +
357
+ ' • org_label: Organization label from the Podio app URL\n' +
358
+ ' • space_label: Space label from the Podio app URL\n' +
359
+ ' • app_label: App label from the Podio app URL\n\n' +
360
+ '2. Or first load an app using get_app_structure with coordinates\n\n' +
361
+ '3. Or set an active app using set_active_app if you have multiple apps loaded\n\n' +
362
+ 'Example: The URL /myorg/myspace/apps/myapp would have:\n' +
363
+ ' org_label: "myorg", space_label: "myspace", app_label: "myapp"';
364
+ throw new PodioStructureError(message, PodioErrorCode.STRUCTURE_NOT_LOADED, {
365
+ metadata: {
366
+ operation,
367
+ suggestion: 'Provide org_label, space_label, and app_label parameters',
368
+ },
369
+ });
370
+ }
371
+ return appContext;
372
+ }
373
+ /**
374
+ * Ensure app structure is loaded using the app structure service.
375
+ * Supports loading multiple apps into memory simultaneously.
376
+ *
377
+ * @private
378
+ * @param args - Arguments with optional coordinates and force_refresh
379
+ * @returns The loaded app structure and field mapper
380
+ */
381
+ async ensureAppStructureLoaded(args = {}) {
382
+ this.ensureServicesAvailable();
383
+ const coordinates = this.appStructureService.resolveAppCoordinates(args);
384
+ if (!coordinates) {
385
+ console.error('App coordinates not available - check environment variables or provide as arguments');
386
+ return null;
387
+ }
388
+ const coordinateKey = this.getCoordinateKey(coordinates);
389
+ // Check if already loaded and not forcing refresh
390
+ if (!args.force_refresh && this.loadedApps.has(coordinateKey)) {
391
+ // Set as active app if not already set
392
+ if (!this.activeAppKey) {
393
+ this.activeAppKey = coordinateKey;
394
+ }
395
+ return this.loadedApps.get(coordinateKey);
396
+ }
397
+ // Load the app structure
398
+ const result = await this.appStructureService.loadAppStructure(coordinates, args.force_refresh);
399
+ // Store in the multi-app map
400
+ this.loadedApps.set(coordinateKey, {
401
+ structure: result.structure,
402
+ fieldMapper: result.fieldMapper,
403
+ });
404
+ // Set as active app if this is the first app loaded or explicitly requested
405
+ if (!this.activeAppKey || args.set_as_active) {
406
+ this.activeAppKey = coordinateKey;
407
+ }
408
+ return result;
409
+ }
410
+ // =================
411
+ // APP MANAGEMENT TOOLS
412
+ // =================
413
+ /**
414
+ * Load and cache the structure of a Podio app.
415
+ * Supports loading multiple apps simultaneously.
416
+ *
417
+ * @private
418
+ * @param args - Arguments containing optional org_label, space_label, app_label, force_refresh, set_as_active
419
+ * @returns MCP tool response with app structure information
420
+ */
421
+ async getAppStructure(args) {
422
+ try {
423
+ const loadedApp = await this.ensureAppStructureLoaded(args);
424
+ if (!loadedApp) {
425
+ return ResponseFormatter.formatError('App structure could not be loaded. Please provide app coordinates (org_label, space_label, app_label) as arguments in your tool call.');
426
+ }
427
+ const coordinates = this.appStructureService.resolveAppCoordinates(args);
428
+ const cachedApp = coordinates
429
+ ? await this.cacheManager.getAppByCoordinates(coordinates)
430
+ : null;
431
+ return ResponseFormatter.formatAppStructure(loadedApp.structure, coordinates, cachedApp || undefined, loadedApp.fieldMapper || undefined);
432
+ }
433
+ catch (error) {
434
+ throw PodioErrorFactory.structureNotLoaded('get app structure');
435
+ }
436
+ }
437
+ /**
438
+ * Cache app structure by coordinates.
439
+ *
440
+ * @private
441
+ */
442
+ async cacheAppStructure(args) {
443
+ const { org_label, space_label, app_label } = args;
444
+ if (!org_label || !space_label || !app_label) {
445
+ throw PodioValidationError.requiredField('org_label, space_label, app_label', 'cache app structure');
446
+ }
447
+ this.ensureServicesAvailable();
448
+ const coordinates = { org_label, space_label, app_label };
449
+ await this.appStructureService.cacheAppStructure(coordinates);
450
+ return ResponseFormatter.formatSuccess(`Successfully cached app structure for ${app_label}!`);
451
+ }
452
+ /**
453
+ * List all cached apps (both in memory and in persistent cache).
454
+ *
455
+ * @private
456
+ */
457
+ async listCachedApps() {
458
+ this.ensureServicesAvailable();
459
+ const persistentCachedApps = await this.appStructureService.getAllCachedApps();
460
+ // Add information about loaded apps in memory
461
+ const loadedAppsInfo = Array.from(this.loadedApps.entries()).map(([key, app]) => ({
462
+ coordinates: key,
463
+ isActive: key === this.activeAppKey,
464
+ appName: app.structure.config?.name || 'Unknown',
465
+ appId: app.structure.app_id,
466
+ fieldsCount: app.structure.fields.length,
467
+ }));
468
+ // Merge both sources of information
469
+ const response = {
470
+ loadedInMemory: loadedAppsInfo,
471
+ cachedInStorage: persistentCachedApps,
472
+ activeApp: this.activeAppKey,
473
+ };
474
+ return ResponseFormatter.formatCachedAppsList(response);
475
+ }
476
+ /**
477
+ * Refresh app cache.
478
+ *
479
+ * @private
480
+ */
481
+ async refreshAppCache(args) {
482
+ this.ensureServicesAvailable();
483
+ const { app_id } = args;
484
+ await this.appStructureService.refreshAppCache(app_id);
485
+ const message = app_id ? `Refreshed cache for app ID ${app_id}` : 'Refreshed all app caches';
486
+ return ResponseFormatter.formatSuccess(message);
487
+ }
488
+ /**
489
+ * Set the active app for operations that don't specify coordinates.
490
+ *
491
+ * @private
492
+ * @param args - App coordinates to set as active
493
+ */
494
+ async setActiveApp(args) {
495
+ const { org_label, space_label, app_label } = args;
496
+ if (!org_label || !space_label || !app_label) {
497
+ throw PodioValidationError.requiredField('org_label, space_label, app_label', 'set active app');
498
+ }
499
+ const coordinateKey = this.getCoordinateKey({ org_label, space_label, app_label });
500
+ // Check if app is loaded
501
+ if (!this.loadedApps.has(coordinateKey)) {
502
+ // Try to load it first
503
+ await this.ensureAppStructureLoaded(args);
504
+ }
505
+ if (!this.loadedApps.has(coordinateKey)) {
506
+ return ResponseFormatter.formatError(`App ${app_label} is not loaded. Please load it first using get_app_structure.`);
507
+ }
508
+ this.activeAppKey = coordinateKey;
509
+ const app = this.loadedApps.get(coordinateKey);
510
+ return ResponseFormatter.formatSuccess(`Active app set to: ${app.structure.config?.name || 'Unknown'} (${app_label}) with ${app.structure.fields.length} fields`);
511
+ }
512
+ /**
513
+ * Clear app cache from both memory and persistent storage.
514
+ * Supports clearing a specific app or all apps.
515
+ *
516
+ * @private
517
+ * @param args - Optional app_id or coordinates to clear specific app
518
+ */
519
+ async clearAppCache(args) {
520
+ this.ensureServicesAvailable();
521
+ const { app_id, org_label, space_label, app_label } = args;
522
+ // Clear from persistent storage
523
+ await this.appStructureService.clearAppCache(app_id);
524
+ // Clear from memory if coordinates provided
525
+ if (org_label && space_label && app_label) {
526
+ const coordinateKey = this.getCoordinateKey({ org_label, space_label, app_label });
527
+ if (this.loadedApps.has(coordinateKey)) {
528
+ this.loadedApps.delete(coordinateKey);
529
+ // Reset active app if it was the one cleared
530
+ if (this.activeAppKey === coordinateKey) {
531
+ this.activeAppKey =
532
+ this.loadedApps.size > 0 ? (this.loadedApps.keys().next().value ?? null) : null;
533
+ }
534
+ }
535
+ }
536
+ else if (!app_id) {
537
+ // Clear all from memory if no specific app specified
538
+ this.loadedApps.clear();
539
+ this.activeAppKey = null;
540
+ }
541
+ const message = app_id
542
+ ? `Cleared cache for app ID ${app_id}`
543
+ : org_label && space_label && app_label
544
+ ? `Cleared cache for ${app_label} in ${space_label}/${org_label}`
545
+ : 'Cleared all app caches';
546
+ return ResponseFormatter.formatSuccess(message);
547
+ }
548
+ // =================
549
+ // ITEM OPERATIONS
550
+ // =================
551
+ /**
552
+ * List items from the configured Podio app with optional filtering.
553
+ * Supports multi-app context by using coordinates or active app.
554
+ *
555
+ * @private
556
+ * @param args - Filter arguments
557
+ * @returns MCP tool response with formatted list of items
558
+ */
559
+ async listItems(args) {
560
+ const { status_filter, responsible_filter, limit = 20, org_label, space_label, app_label, } = args;
561
+ const appContext = await this.getAppContextForOperation(args, 'list items');
562
+ const coordinates = this.appStructureService.resolveAppCoordinates(org_label && space_label && app_label ? { org_label, space_label, app_label } : {});
563
+ const result = await this.itemService.listItems(appContext.structure.app_id, appContext.fieldMapper, { status_filter, responsible_filter, limit }, coordinates || undefined);
564
+ return ResponseFormatter.formatItemsList(result.items, result.filteredItems, appContext.fieldMapper, responsible_filter);
565
+ }
566
+ /**
567
+ * Create a new item in the Podio app.
568
+ * Supports multi-app context by using coordinates or active app.
569
+ *
570
+ * @private
571
+ * @param args - Item data
572
+ * @returns MCP tool response with created item information
573
+ */
574
+ async createItem(args) {
575
+ const { title, description, status, responsible, project, epic, org_label, space_label, app_label, } = args;
576
+ const appContext = await this.getAppContextForOperation(args, 'create item');
577
+ const coordinates = this.appStructureService.resolveAppCoordinates(org_label && space_label && app_label ? { org_label, space_label, app_label } : {});
578
+ const newItem = await this.itemService.createItem(appContext.structure.app_id, appContext.fieldMapper, { title, description, status, responsible, project, epic }, coordinates || undefined);
579
+ return ResponseFormatter.formatItemCreated(newItem, appContext.fieldMapper);
580
+ }
581
+ /**
582
+ * Update an existing item in the Podio app.
583
+ *
584
+ * @private
585
+ * @param args - Update data
586
+ * @returns MCP tool response with update confirmation
587
+ */
588
+ async updateItem(args) {
589
+ const { item_id, title, description, status, responsible, project, epic, org_label, space_label, app_label, } = args;
590
+ if (!item_id) {
591
+ throw PodioValidationError.requiredField('item_id', 'update item');
592
+ }
593
+ const appContext = await this.getAppContextForOperation(args, 'update item');
594
+ const coordinates = this.appStructureService.resolveAppCoordinates(org_label && space_label && app_label ? { org_label, space_label, app_label } : {});
595
+ await this.itemService.updateItem(item_id, appContext.fieldMapper, { title, description, status, responsible, project, epic }, appContext.structure.app_id, coordinates || undefined);
596
+ return ResponseFormatter.formatSuccess(`Successfully updated item ${item_id}!`);
597
+ }
598
+ /**
599
+ * Delete an item from the Podio app.
600
+ *
601
+ * @private
602
+ * @param args - Arguments containing item_id
603
+ * @returns MCP tool response with deletion confirmation
604
+ */
605
+ async deleteItem(args) {
606
+ this.ensureServicesAvailable();
607
+ const { item_id } = args;
608
+ if (!item_id) {
609
+ throw PodioValidationError.requiredField('item_id', 'delete item');
610
+ }
611
+ await this.itemService.deleteItem(item_id);
612
+ return ResponseFormatter.formatSuccess(`Successfully deleted item ${item_id}!`);
613
+ }
614
+ /**
615
+ * Get detailed information about a specific item.
616
+ *
617
+ * @private
618
+ * @param args - Arguments containing item_id
619
+ * @returns MCP tool response with detailed item information
620
+ */
621
+ async getItemDetails(args) {
622
+ // Don't call ensureAppStructureLoaded here - it should already be loaded
623
+ this.ensureServicesAvailable();
624
+ const { item_id } = args;
625
+ if (!item_id) {
626
+ throw PodioValidationError.requiredField('item_id', 'get item details');
627
+ }
628
+ // Use active app for field mapper if available
629
+ const activeApp = this.getActiveApp();
630
+ try {
631
+ const item = await this.itemService.getItem(item_id);
632
+ // If we have a field mapper, use it for rich formatting
633
+ if (activeApp?.fieldMapper) {
634
+ return ResponseFormatter.formatItemDetails(item, activeApp.fieldMapper);
635
+ }
636
+ // Otherwise, return basic item information without field mapping
637
+ const ticketNum = item.app_item_id || item.app_item_id_formatted;
638
+ return {
639
+ content: [
640
+ {
641
+ type: 'text',
642
+ text: `📋 **Item Details**\n\n` +
643
+ `**Ticket Number:** #${ticketNum}\n` +
644
+ `**Global ID:** ${item.item_id}\n` +
645
+ `**Created:** ${item.created_on}\n` +
646
+ `**Link:** ${item.link}\n\n` +
647
+ `⚠️ Note: Load an app structure with get_app_structure to see detailed field values.`,
648
+ },
649
+ ],
650
+ };
651
+ }
652
+ catch (error) {
653
+ // Add helpful error message for 404
654
+ if (error.status === 404 || error.message?.includes('404')) {
655
+ throw new Error(`Item with global ID ${item_id} not found. If this is a ticket/item number, use get_item_by_app_item_id instead.`);
656
+ }
657
+ throw error;
658
+ }
659
+ }
660
+ /**
661
+ * Get detailed information about a specific item using its app item ID.
662
+ *
663
+ * @private
664
+ * @param args - Arguments containing app_item_id
665
+ * @returns MCP tool response with detailed item information
666
+ */
667
+ async getItemByAppItemId(args) {
668
+ const { app_item_id } = args;
669
+ if (!app_item_id) {
670
+ throw PodioValidationError.requiredField('app_item_id', 'get item by app item ID');
671
+ }
672
+ const appContext = await this.getAppContextForOperation(args, 'get item by app item ID');
673
+ const item = await this.itemService.getItemByAppItemId(appContext.structure.app_id, app_item_id);
674
+ return ResponseFormatter.formatItemDetails(item, appContext.fieldMapper);
675
+ }
676
+ /**
677
+ * Update an item using its app item ID.
678
+ *
679
+ * @private
680
+ * @param args - Arguments containing app_item_id and update data
681
+ * @returns MCP tool response with update confirmation
682
+ */
683
+ async updateItemByAppItemId(args) {
684
+ const { app_item_id, title, description, status, responsible, project, epic, org_label, space_label, app_label, } = args;
685
+ if (!app_item_id) {
686
+ throw PodioValidationError.requiredField('app_item_id', 'update item by app item ID');
687
+ }
688
+ const appContext = await this.getAppContextForOperation(args, 'update item by app item ID');
689
+ // First get the item to get its global ID
690
+ const item = await this.itemService.getItemByAppItemId(appContext.structure.app_id, app_item_id);
691
+ // Then update using the global ID
692
+ const coordinates = this.appStructureService.resolveAppCoordinates(org_label && space_label && app_label ? { org_label, space_label, app_label } : {});
693
+ await this.itemService.updateItem(item.item_id, appContext.fieldMapper, { title, description, status, responsible, project, epic }, appContext.structure.app_id, coordinates || undefined);
694
+ return {
695
+ content: [
696
+ {
697
+ type: 'text',
698
+ text: `✅ Item (Ticket #${app_item_id}) updated successfully`,
699
+ },
700
+ ],
701
+ };
702
+ }
703
+ /**
704
+ * Delete an item using its app item ID.
705
+ *
706
+ * @private
707
+ * @param args - Arguments containing app_item_id
708
+ * @returns MCP tool response with delete confirmation
709
+ */
710
+ async deleteItemByAppItemId(args) {
711
+ // Don't call ensureAppStructureLoaded here - it should already be loaded
712
+ this.ensureServicesAvailable();
713
+ const { app_item_id } = args;
714
+ if (!app_item_id) {
715
+ throw PodioValidationError.requiredField('app_item_id', 'delete item by app item ID');
716
+ }
717
+ const appContext = await this.getAppContextForOperation(args, 'delete item by app item ID');
718
+ // First get the item to get its global ID
719
+ const item = await this.itemService.getItemByAppItemId(appContext.structure.app_id, app_item_id);
720
+ // Then delete using the global ID
721
+ await this.itemService.deleteItem(item.item_id);
722
+ return {
723
+ content: [
724
+ {
725
+ type: 'text',
726
+ text: `✅ Item (Ticket #${app_item_id}) deleted successfully`,
727
+ },
728
+ ],
729
+ };
730
+ }
731
+ // =================
732
+ // TASK MANAGEMENT
733
+ // =================
734
+ /**
735
+ * List Podio tasks with optional filtering.
736
+ *
737
+ * @private
738
+ * @param args - Filter arguments
739
+ * @returns MCP tool response with formatted list of tasks
740
+ */
741
+ async listTasks(args) {
742
+ this.ensureServicesAvailable();
743
+ const { assigned_to, status, limit = 20 } = args;
744
+ // Get space ID for task filtering (if available)
745
+ let spaceId;
746
+ const activeApp = this.getActiveApp();
747
+ if (activeApp && activeApp.structure.space_id) {
748
+ spaceId = activeApp.structure.space_id;
749
+ }
750
+ const tasks = await this.taskService.listTasks({ assigned_to, status, limit }, spaceId);
751
+ return ResponseFormatter.formatTasksList(tasks);
752
+ }
753
+ /**
754
+ * Create a new task in Podio.
755
+ *
756
+ * @private
757
+ * @param args - Task data
758
+ * @returns MCP tool response with created task information
759
+ */
760
+ async createTask(args) {
761
+ this.ensureServicesAvailable();
762
+ const { text, description, due_date, assigned_to, ref_type, ref_id } = args;
763
+ const newTask = await this.taskService.createTask({
764
+ text,
765
+ description,
766
+ due_date,
767
+ assigned_to,
768
+ ref_type,
769
+ ref_id,
770
+ });
771
+ return ResponseFormatter.formatTaskCreated(newTask);
772
+ }
773
+ /**
774
+ * Create a new task attached to a specific Podio item.
775
+ *
776
+ * @private
777
+ * @param args - Task data with item_id
778
+ * @returns MCP tool response with created task information
779
+ */
780
+ async createTaskForItem(args) {
781
+ this.ensureServicesAvailable();
782
+ const { item_id, text, description, due_date, assigned_to } = args;
783
+ const newTask = await this.taskService.createTaskForItem(item_id, {
784
+ text,
785
+ description,
786
+ due_date,
787
+ assigned_to,
788
+ });
789
+ return ResponseFormatter.formatTaskCreated(newTask, item_id);
790
+ }
791
+ /**
792
+ * Update an existing task in Podio.
793
+ *
794
+ * @private
795
+ * @param args - Task update data
796
+ * @returns MCP tool response with update confirmation
797
+ */
798
+ async updateTask(args) {
799
+ this.ensureServicesAvailable();
800
+ const { task_id, text, description, due_date, completed } = args;
801
+ const updatedTask = await this.taskService.updateTask(task_id, {
802
+ text,
803
+ description,
804
+ due_date,
805
+ completed,
806
+ });
807
+ return ResponseFormatter.formatTaskUpdated(updatedTask);
808
+ }
809
+ /**
810
+ * Delete a task from Podio.
811
+ *
812
+ * @private
813
+ * @param args - Arguments containing task_id
814
+ * @returns MCP tool response with deletion confirmation
815
+ */
816
+ async deleteTask(args) {
817
+ this.ensureServicesAvailable();
818
+ const { task_id } = args;
819
+ await this.taskService.deleteTask(task_id);
820
+ return ResponseFormatter.formatSuccess(`Successfully deleted task ${task_id}!`);
821
+ }
822
+ /**
823
+ * Get detailed information about a specific task.
824
+ *
825
+ * @private
826
+ * @param args - Arguments containing task_id
827
+ * @returns MCP tool response with detailed task information
828
+ */
829
+ async getTaskDetails(args) {
830
+ this.ensureServicesAvailable();
831
+ const { task_id } = args;
832
+ const task = await this.taskService.getTaskDetails(task_id);
833
+ return ResponseFormatter.formatTaskDetails(task);
834
+ }
835
+ // =================
836
+ // PROJECT/EPIC MANAGEMENT
837
+ // =================
838
+ /**
839
+ * List all available projects.
840
+ *
841
+ * @private
842
+ * @param args - Arguments with optional refresh_cache
843
+ * @returns MCP tool response with formatted list of projects
844
+ */
845
+ async listProjects(args) {
846
+ this.ensureServicesAvailable();
847
+ const appContext = await this.getAppContextForOperation(args, 'list projects');
848
+ const { refresh_cache = false } = args;
849
+ const projects = await this.projectEpicService.listProjects(appContext.structure.app_id, appContext.fieldMapper, refresh_cache);
850
+ return ResponseFormatter.formatProjectEpicList(projects, 'Projects');
851
+ }
852
+ /**
853
+ * List all available epics.
854
+ *
855
+ * @private
856
+ * @param args - Arguments with optional refresh_cache
857
+ * @returns MCP tool response with formatted list of epics
858
+ */
859
+ async listEpics(args) {
860
+ this.ensureServicesAvailable();
861
+ const appContext = await this.getAppContextForOperation(args, 'list epics');
862
+ const { refresh_cache = false } = args;
863
+ const epics = await this.projectEpicService.listEpics(appContext.structure.app_id, appContext.fieldMapper, refresh_cache);
864
+ return ResponseFormatter.formatProjectEpicList(epics, 'Epics');
865
+ }
866
+ /**
867
+ * Suggest appropriate project and epic based on item details using sophisticated AI-powered matching.
868
+ *
869
+ * This function implements a comprehensive suggestion system that analyzes input text against
870
+ * cached projects and epics using multiple matching strategies and weighted scoring algorithms.
871
+ *
872
+ * ## Matching Algorithm
873
+ *
874
+ * The suggestion system uses a hierarchical matching approach with weighted scoring:
875
+ *
876
+ * ### Scoring Weights
877
+ * - **Title matching**: 1.0x (full weight)
878
+ * - **Description matching**: 0.5x (reduced weight as descriptions are less precise)
879
+ * - **Label matching**: 0.3x (minimal weight as labels are often generic)
880
+ *
881
+ * ### Matching Hierarchy
882
+ * 1. **Exact match**: Perfect string match (score: 1.0)
883
+ * 2. **Prefix match**: Input matches start of target (score: 0.9)
884
+ * 3. **Contains match**: Target contains input anywhere (score: 0.7)
885
+ * 4. **Fuzzy match**: Levenshtein distance-based similarity (score: 0.0-0.6)
886
+ *
887
+ * ### Levenshtein Distance Fuzzy Matching
888
+ * When exact/prefix/contains matching fails, the system uses Levenshtein distance
889
+ * to calculate string similarity: `1 - (editDistance / maxStringLength)`
890
+ * This enables matching of typos, abbreviations, and related terms.
891
+ *
892
+ * ## Configuration Parameters
893
+ * - **minSimilarityScore**: 0.3 (filters out weak matches)
894
+ * - **maxSuggestions**: 10 (limits results for performance)
895
+ * - **Cache TTL**: 30 minutes (balances freshness vs performance)
896
+ *
897
+ * ## Cache Behavior
898
+ * - Projects and epics are cached for 30 minutes after first fetch
899
+ * - Cache keys are based on app ID for workspace isolation
900
+ * - Automatic cache refresh on API structure mismatches
901
+ * - Memory-based storage for fast lookups during suggestion scoring
902
+ *
903
+ * @example
904
+ * Input: "API authentication refactor"
905
+ * Matches:
906
+ * - Project: "Authentication System" (0.85 - title similarity)
907
+ * - Epic: "API Improvements" (0.72 - partial title match)
908
+ *
909
+ * @example
910
+ * Input: "database migration task"
911
+ * Matches:
912
+ * - Project: "Database Modernization" (0.68 - fuzzy title match)
913
+ * - Epic: "Data Migration" (0.91 - strong title match)
914
+ *
915
+ * @private
916
+ * @param args - Arguments containing title and optional description
917
+ * @param args.title - The title of the item to suggest projects/epics for (required)
918
+ * @param args.description - Optional description providing additional context for matching
919
+ * @returns MCP tool response with ranked suggestions including:
920
+ * - Matched projects with similarity scores and reasons
921
+ * - Matched epics with similarity scores and reasons
922
+ * - Empty arrays if no matches above similarity threshold found
923
+ * @throws {PodioValidationError} If title parameter is missing or empty
924
+ * @throws {PodioStructureError} If app structure is not loaded
925
+ * @throws {PodioApiError} If project/epic data cannot be fetched from cache or API
926
+ */
927
+ async suggestProjectEpic(args) {
928
+ this.ensureServicesAvailable();
929
+ const { title, description = '' } = args;
930
+ if (!title) {
931
+ throw PodioValidationError.requiredField('title', 'suggest project epic');
932
+ }
933
+ const activeApp = this.getActiveApp();
934
+ const suggestions = await this.projectEpicService.getSuggestions(title, description, activeApp?.structure.app_id);
935
+ return ResponseFormatter.formatProjectEpicSuggestions(title, suggestions.projects, suggestions.epics);
936
+ }
937
+ // =================
938
+ // UTILITY TOOLS
939
+ // =================
940
+ /**
941
+ * Inspect the structure of fields in the app.
942
+ *
943
+ * @private
944
+ * @param args - Arguments with optional field_name
945
+ * @returns MCP tool response with field structure information
946
+ */
947
+ async inspectFieldStructure(args) {
948
+ const appContext = await this.getAppContextForOperation(args, 'inspect field structure');
949
+ const { field_name } = args;
950
+ return ResponseFormatter.formatFieldStructure(appContext.structure, appContext.fieldMapper, field_name);
951
+ }
952
+ /**
953
+ * List all members of the current space.
954
+ *
955
+ * @private
956
+ * @param args - Arguments with optional refresh_cache
957
+ * @returns MCP tool response with formatted list of space members
958
+ */
959
+ async listSpaceMembers(args) {
960
+ await this.ensureAppStructureLoaded();
961
+ this.ensureServicesAvailable();
962
+ const { refresh_cache = false } = args;
963
+ const activeApp = this.getActiveApp();
964
+ if (!activeApp || !activeApp.structure.space_id) {
965
+ throw PodioStructureError.notLoaded('Space information not available');
966
+ }
967
+ const spaceId = activeApp.structure.space_id;
968
+ let members;
969
+ if (!refresh_cache && (await this.cacheManager.hasSpaceMembers(spaceId))) {
970
+ members = await this.cacheManager.getSpaceMembers(spaceId);
971
+ }
972
+ else {
973
+ // Fetch members from API
974
+ members = await this.apiClient.getSpaceMembers(spaceId);
975
+ await this.cacheManager.setSpaceMembers(spaceId, members);
976
+ }
977
+ return ResponseFormatter.formatSpaceMembersList(members);
978
+ }
979
+ // =================
980
+ // NOTIFICATION MANAGEMENT
981
+ // =================
982
+ /**
983
+ * List Podio notifications with optional filtering.
984
+ *
985
+ * @private
986
+ * @param args - Filter arguments
987
+ * @returns MCP tool response with formatted list of notifications
988
+ */
989
+ async listNotifications(args) {
990
+ this.ensureServicesAvailable();
991
+ const { status, type, viewed, limit = 20, offset = 0, created_from, created_to, space_id, app_id, } = args;
992
+ const filters = {
993
+ status,
994
+ type,
995
+ viewed,
996
+ limit,
997
+ offset,
998
+ created_from,
999
+ created_to,
1000
+ space_id,
1001
+ app_id,
1002
+ };
1003
+ // Remove undefined and null values
1004
+ Object.keys(filters).forEach((key) => filters[key] == null && delete filters[key]);
1005
+ const response = await this.notificationService.listNotifications(filters);
1006
+ // Filter notifications if specific criteria are requested
1007
+ let filteredNotifications = response.notifications;
1008
+ if (viewed === false) {
1009
+ filteredNotifications = this.notificationService.filterNotifications(response.notifications, { unreadOnly: true });
1010
+ }
1011
+ return ResponseFormatter.formatNotificationsList(response.notifications, filteredNotifications, response.total, viewed === false);
1012
+ }
1013
+ /**
1014
+ * Get detailed information about a specific notification.
1015
+ *
1016
+ * @private
1017
+ * @param args - Arguments containing notification_id
1018
+ * @returns MCP tool response with detailed notification information
1019
+ */
1020
+ async getNotificationDetails(args) {
1021
+ this.ensureServicesAvailable();
1022
+ const { notification_id } = args;
1023
+ if (!notification_id) {
1024
+ throw PodioValidationError.requiredField('notification_id', 'get notification details');
1025
+ }
1026
+ const notification = await this.notificationService.getNotification(notification_id);
1027
+ return ResponseFormatter.formatNotificationDetails(notification);
1028
+ }
1029
+ /**
1030
+ * Get unread notification count.
1031
+ *
1032
+ * @private
1033
+ * @param args - Empty arguments object
1034
+ * @returns MCP tool response with unread count information
1035
+ */
1036
+ async getUnreadCount(args) {
1037
+ this.ensureServicesAvailable();
1038
+ const count = await this.notificationService.getUnreadCount();
1039
+ return ResponseFormatter.formatUnreadCount(count);
1040
+ }
1041
+ /**
1042
+ * Get notification settings for the current user.
1043
+ *
1044
+ * @private
1045
+ * @param args - Empty arguments object
1046
+ * @returns MCP tool response with notification settings
1047
+ */
1048
+ async getNotificationSettings(args) {
1049
+ this.ensureServicesAvailable();
1050
+ const settings = await this.notificationService.getNotificationSettings();
1051
+ return ResponseFormatter.formatNotificationSettings(settings);
1052
+ }
1053
+ // =================
1054
+ // SEARCH OPERATIONS
1055
+ // =================
1056
+ /**
1057
+ * Main search tool with scope selection and filtering
1058
+ *
1059
+ * @private
1060
+ * @param args - Search arguments
1061
+ * @returns MCP tool response with search results
1062
+ */
1063
+ async searchPodio(args) {
1064
+ this.ensureServicesAvailable();
1065
+ const { query, scope = 'global', type, space_id, app_id, org_id, limit = 20, offset = 0, created_from, created_to, fields, group_results = false, } = args;
1066
+ if (!query || query.trim().length === 0) {
1067
+ throw PodioValidationError.requiredField('query', 'search');
1068
+ }
1069
+ // Parse type filters (can be comma-separated)
1070
+ let searchTypes;
1071
+ if (type) {
1072
+ searchTypes = type.split(',').map((t) => t.trim());
1073
+ }
1074
+ // Parse field filters (can be comma-separated)
1075
+ let searchFields;
1076
+ if (fields) {
1077
+ searchFields = fields.split(',').map((f) => f.trim());
1078
+ }
1079
+ // Build search filters
1080
+ const filters = {
1081
+ query,
1082
+ scope,
1083
+ type: searchTypes,
1084
+ space_id,
1085
+ app_id,
1086
+ org_id,
1087
+ limit,
1088
+ offset,
1089
+ created_from,
1090
+ created_to,
1091
+ fields: searchFields,
1092
+ };
1093
+ // Build search context from current app structure
1094
+ const activeApp = this.getActiveApp();
1095
+ const context = {
1096
+ space_id: activeApp ? activeApp.structure.space_id : undefined,
1097
+ app_id: activeApp ? activeApp.structure.app_id : undefined,
1098
+ org_id: activeApp ? activeApp.structure.org_id : undefined,
1099
+ };
1100
+ try {
1101
+ if (group_results) {
1102
+ const groupedResults = await this.searchService.searchWithGrouping(filters, context);
1103
+ return ResponseFormatter.formatGroupedSearchResults(groupedResults);
1104
+ }
1105
+ else {
1106
+ const searchResponse = await this.searchService.search(filters, context);
1107
+ return ResponseFormatter.formatSearchResults(searchResponse);
1108
+ }
1109
+ }
1110
+ catch (error) {
1111
+ if (error instanceof Error) {
1112
+ return ResponseFormatter.formatError(`Search failed: ${error.message}`);
1113
+ }
1114
+ throw error;
1115
+ }
1116
+ }
1117
+ /**
1118
+ * Quick search within a specific app
1119
+ *
1120
+ * @private
1121
+ * @param args - Search arguments
1122
+ * @returns MCP tool response with search results
1123
+ */
1124
+ async searchInApp(args) {
1125
+ this.ensureServicesAvailable();
1126
+ const { query, app_id, type, limit = 20, offset = 0, fields } = args;
1127
+ if (!query || query.trim().length === 0) {
1128
+ throw PodioValidationError.requiredField('query', 'search in app');
1129
+ }
1130
+ // Use provided app_id or current app context
1131
+ const activeApp = this.getActiveApp();
1132
+ const targetAppId = app_id || (activeApp ? activeApp.structure.app_id : null);
1133
+ if (!targetAppId) {
1134
+ return ResponseFormatter.formatError('No app specified and no current app context available. Please provide app_id or ensure app structure is loaded.');
1135
+ }
1136
+ // Parse type and field filters
1137
+ let searchTypes;
1138
+ if (type) {
1139
+ searchTypes = type.split(',').map((t) => t.trim());
1140
+ }
1141
+ let searchFields;
1142
+ if (fields) {
1143
+ searchFields = fields.split(',').map((f) => f.trim());
1144
+ }
1145
+ try {
1146
+ const searchResponse = await this.searchService.searchInApp(targetAppId, query, {
1147
+ type: searchTypes,
1148
+ limit,
1149
+ offset,
1150
+ fields: searchFields,
1151
+ });
1152
+ return ResponseFormatter.formatSearchResults(searchResponse);
1153
+ }
1154
+ catch (error) {
1155
+ if (error instanceof Error) {
1156
+ return ResponseFormatter.formatError(`App search failed: ${error.message}`);
1157
+ }
1158
+ throw error;
1159
+ }
1160
+ }
1161
+ /**
1162
+ * Quick search within a specific space
1163
+ *
1164
+ * @private
1165
+ * @param args - Search arguments
1166
+ * @returns MCP tool response with search results
1167
+ */
1168
+ async searchInSpace(args) {
1169
+ this.ensureServicesAvailable();
1170
+ const { query, space_id, type, limit = 20, offset = 0, fields } = args;
1171
+ if (!query || query.trim().length === 0) {
1172
+ throw PodioValidationError.requiredField('query', 'search in space');
1173
+ }
1174
+ // Use provided space_id or current space context
1175
+ const activeApp = this.getActiveApp();
1176
+ const targetSpaceId = space_id || (activeApp ? activeApp.structure.space_id : null);
1177
+ if (!targetSpaceId) {
1178
+ return ResponseFormatter.formatError('No space specified and no current space context available. Please provide space_id or ensure app structure is loaded.');
1179
+ }
1180
+ // Parse type and field filters
1181
+ let searchTypes;
1182
+ if (type) {
1183
+ searchTypes = type.split(',').map((t) => t.trim());
1184
+ }
1185
+ let searchFields;
1186
+ if (fields) {
1187
+ searchFields = fields.split(',').map((f) => f.trim());
1188
+ }
1189
+ try {
1190
+ const searchResponse = await this.searchService.searchInSpace(targetSpaceId, query, {
1191
+ type: searchTypes,
1192
+ limit,
1193
+ offset,
1194
+ fields: searchFields,
1195
+ });
1196
+ return ResponseFormatter.formatSearchResults(searchResponse);
1197
+ }
1198
+ catch (error) {
1199
+ if (error instanceof Error) {
1200
+ return ResponseFormatter.formatError(`Space search failed: ${error.message}`);
1201
+ }
1202
+ throw error;
1203
+ }
1204
+ }
1205
+ /**
1206
+ * Get search history
1207
+ *
1208
+ * @private
1209
+ * @param args - Arguments with optional limit
1210
+ * @returns MCP tool response with search history
1211
+ */
1212
+ async getSearchHistory(args) {
1213
+ this.ensureServicesAvailable();
1214
+ const { limit = 10 } = args;
1215
+ try {
1216
+ const recentSearches = await this.searchService.getRecentSearches(limit);
1217
+ return ResponseFormatter.formatSearchHistory(recentSearches);
1218
+ }
1219
+ catch (error) {
1220
+ if (error instanceof Error) {
1221
+ return ResponseFormatter.formatError(`Failed to get search history: ${error.message}`);
1222
+ }
1223
+ throw error;
1224
+ }
1225
+ }
1226
+ /**
1227
+ * Clear search history
1228
+ *
1229
+ * @private
1230
+ * @param args - Empty arguments object
1231
+ * @returns MCP tool response with success confirmation
1232
+ */
1233
+ async clearSearchHistory(args) {
1234
+ this.ensureServicesAvailable();
1235
+ try {
1236
+ await this.searchService.clearSearchHistory();
1237
+ return ResponseFormatter.formatSuccess('Search history cleared successfully!');
1238
+ }
1239
+ catch (error) {
1240
+ if (error instanceof Error) {
1241
+ return ResponseFormatter.formatError(`Failed to clear search history: ${error.message}`);
1242
+ }
1243
+ throw error;
1244
+ }
1245
+ }
1246
+ // =================
1247
+ // COMMENT & ACTIVITY OPERATIONS
1248
+ // =================
1249
+ /**
1250
+ * List all comments for a specific item.
1251
+ *
1252
+ * @private
1253
+ * @param args - Arguments containing item_id
1254
+ * @returns MCP tool response with list of comments
1255
+ */
1256
+ async listItemComments(args) {
1257
+ this.ensureServicesAvailable();
1258
+ const { item_id } = args;
1259
+ if (!item_id) {
1260
+ throw PodioValidationError.requiredField('item_id', 'list item comments');
1261
+ }
1262
+ const comments = await this.commentService.listItemComments(item_id);
1263
+ return ResponseFormatter.formatItemCommentsList(comments);
1264
+ }
1265
+ /**
1266
+ * Create a new comment on an item.
1267
+ *
1268
+ * @private
1269
+ * @param args - Arguments containing item_id and text
1270
+ * @returns MCP tool response with created comment
1271
+ */
1272
+ async createItemComment(args) {
1273
+ this.ensureServicesAvailable();
1274
+ const { item_id, text } = args;
1275
+ if (!item_id) {
1276
+ throw PodioValidationError.requiredField('item_id', 'create item comment');
1277
+ }
1278
+ if (!text) {
1279
+ throw PodioValidationError.requiredField('text', 'create item comment');
1280
+ }
1281
+ const comment = await this.commentService.createItemComment(item_id, text);
1282
+ return ResponseFormatter.formatCommentCreated(comment);
1283
+ }
1284
+ /**
1285
+ * Get details of a specific comment.
1286
+ *
1287
+ * @private
1288
+ * @param args - Arguments containing comment_id
1289
+ * @returns MCP tool response with comment details
1290
+ */
1291
+ async getCommentDetails(args) {
1292
+ this.ensureServicesAvailable();
1293
+ const { comment_id } = args;
1294
+ if (!comment_id) {
1295
+ throw PodioValidationError.requiredField('comment_id', 'get comment details');
1296
+ }
1297
+ const comment = await this.commentService.getComment(comment_id);
1298
+ return ResponseFormatter.formatCommentDetails(comment);
1299
+ }
1300
+ /**
1301
+ * Update an existing comment.
1302
+ *
1303
+ * @private
1304
+ * @param args - Arguments containing comment_id and text
1305
+ * @returns MCP tool response with success confirmation
1306
+ */
1307
+ async updateComment(args) {
1308
+ this.ensureServicesAvailable();
1309
+ const { comment_id, text } = args;
1310
+ if (!comment_id) {
1311
+ throw PodioValidationError.requiredField('comment_id', 'update comment');
1312
+ }
1313
+ if (!text) {
1314
+ throw PodioValidationError.requiredField('text', 'update comment');
1315
+ }
1316
+ await this.commentService.updateComment(comment_id, text);
1317
+ return ResponseFormatter.formatSuccess(`Successfully updated comment ${comment_id}!`);
1318
+ }
1319
+ /**
1320
+ * Delete a comment.
1321
+ *
1322
+ * @private
1323
+ * @param args - Arguments containing comment_id
1324
+ * @returns MCP tool response with deletion confirmation
1325
+ */
1326
+ async deleteComment(args) {
1327
+ this.ensureServicesAvailable();
1328
+ const { comment_id } = args;
1329
+ if (!comment_id) {
1330
+ throw PodioValidationError.requiredField('comment_id', 'delete comment');
1331
+ }
1332
+ await this.commentService.deleteComment(comment_id);
1333
+ return ResponseFormatter.formatSuccess(`Successfully deleted comment ${comment_id}!`);
1334
+ }
1335
+ /**
1336
+ * List all activity/revisions for a specific item.
1337
+ *
1338
+ * @private
1339
+ * @param args - Arguments containing item_id
1340
+ * @returns MCP tool response with item activity
1341
+ */
1342
+ async listItemActivity(args) {
1343
+ this.ensureServicesAvailable();
1344
+ const { item_id } = args;
1345
+ if (!item_id) {
1346
+ throw PodioValidationError.requiredField('item_id', 'list item activity');
1347
+ }
1348
+ const activity = await this.itemService.getItemActivity(item_id);
1349
+ return ResponseFormatter.formatItemActivity(activity);
1350
+ }
1351
+ /**
1352
+ * Get details of a specific item revision.
1353
+ *
1354
+ * @private
1355
+ * @param args - Arguments containing item_id and revision_id
1356
+ * @returns MCP tool response with revision details
1357
+ */
1358
+ async getItemRevision(args) {
1359
+ this.ensureServicesAvailable();
1360
+ const { item_id, revision_id } = args;
1361
+ if (!item_id) {
1362
+ throw PodioValidationError.requiredField('item_id', 'get item revision');
1363
+ }
1364
+ if (!revision_id) {
1365
+ throw PodioValidationError.requiredField('revision_id', 'get item revision');
1366
+ }
1367
+ const revision = await this.itemService.getItemRevision(item_id, revision_id);
1368
+ return ResponseFormatter.formatItemRevisionDetails(revision);
1369
+ }
1370
+ /**
1371
+ * Get the difference between two item revisions.
1372
+ *
1373
+ * @private
1374
+ * @param args - Arguments containing item_id, from_revision, and to_revision
1375
+ * @returns MCP tool response with revision differences
1376
+ */
1377
+ async getItemRevisionDiff(args) {
1378
+ this.ensureServicesAvailable();
1379
+ const { item_id, from_revision, to_revision } = args;
1380
+ if (!item_id) {
1381
+ throw PodioValidationError.requiredField('item_id', 'get item revision diff');
1382
+ }
1383
+ if (!from_revision) {
1384
+ throw PodioValidationError.requiredField('from_revision', 'get item revision diff');
1385
+ }
1386
+ if (!to_revision) {
1387
+ throw PodioValidationError.requiredField('to_revision', 'get item revision diff');
1388
+ }
1389
+ const diff = await this.itemService.getItemRevisionDiff(item_id, from_revision, to_revision);
1390
+ return ResponseFormatter.formatItemRevisionDiff(diff);
1391
+ }
1392
+ // ============================================================================
1393
+ // CODE EXECUTION HANDLERS
1394
+ // ============================================================================
1395
+ /**
1396
+ * Execute TypeScript/JavaScript code in a sandboxed Deno environment.
1397
+ *
1398
+ * This tool provides 60-95% token reduction for complex multi-step operations
1399
+ * by processing data in the execution environment instead of passing it
1400
+ * through the model context.
1401
+ *
1402
+ * @private
1403
+ * @param args - Arguments containing code, timeout, and optional context
1404
+ * @returns Code execution result
1405
+ */
1406
+ async executeCode(args) {
1407
+ if (!this.codeExecutionService) {
1408
+ throw new PodioConfigError('Code execution service not initialized');
1409
+ }
1410
+ const { code, timeout, context } = args;
1411
+ if (!code) {
1412
+ throw PodioValidationError.requiredField('code', 'execute code');
1413
+ }
1414
+ const result = await this.codeExecutionService.executeCode(code, {
1415
+ timeout,
1416
+ context,
1417
+ });
1418
+ // Format the response
1419
+ if (result.success) {
1420
+ return {
1421
+ content: [
1422
+ {
1423
+ type: 'text',
1424
+ text: `## Code Execution Result\n\n**Status:** Success\n**Execution Time:** ${result.executionTime}ms\n\n### Result\n\`\`\`json\n${JSON.stringify(result.result, null, 2)}\n\`\`\`${result.stdout ? `\n\n### Output\n\`\`\`\n${result.stdout}\n\`\`\`` : ''}`,
1425
+ },
1426
+ ],
1427
+ };
1428
+ }
1429
+ else {
1430
+ return {
1431
+ content: [
1432
+ {
1433
+ type: 'text',
1434
+ text: `## Code Execution Failed\n\n**Status:** Error\n**Execution Time:** ${result.executionTime}ms\n\n### Error\n\`\`\`\n${result.error}\n\`\`\`${result.stderr ? `\n\n### Stderr\n\`\`\`\n${result.stderr}\n\`\`\`` : ''}`,
1435
+ },
1436
+ ],
1437
+ isError: true,
1438
+ };
1439
+ }
1440
+ }
1441
+ /**
1442
+ * List all available functions in the filesystem code execution API.
1443
+ *
1444
+ * @private
1445
+ * @returns List of available functions organized by category
1446
+ */
1447
+ async listCodeFunctions() {
1448
+ if (!this.codeExecutionService) {
1449
+ throw new PodioConfigError('Code execution service not initialized');
1450
+ }
1451
+ const functions = await this.codeExecutionService.listAvailableFunctions();
1452
+ const example = this.codeExecutionService.getExampleUsage();
1453
+ let text = `## Available Code Execution Functions\n\nThese functions can be imported from \`mcp-servers/podio/\` when using the \`execute_code\` tool.\n\n`;
1454
+ for (const [category, funcs] of Object.entries(functions)) {
1455
+ text += `### ${category.charAt(0).toUpperCase() + category.slice(1)}\n\n`;
1456
+ for (const func of funcs) {
1457
+ text += `- \`${func}\`\n`;
1458
+ }
1459
+ text += '\n';
1460
+ }
1461
+ text += `## Example Usage\n\n\`\`\`typescript\n${example}\n\`\`\`\n\n`;
1462
+ text += `## Token Savings\n\nUsing code execution can reduce token usage by **60-95%** for complex operations:\n\n`;
1463
+ text += `| Operation | Traditional | Code Exec | Savings |\n`;
1464
+ text += `|-----------|------------|-----------|--------|\n`;
1465
+ text += `| Create w/ References | 16,500 tok | 500 tok | **97%** |\n`;
1466
+ text += `| Bulk Processing | 20,000 tok | 1,000 tok | **95%** |\n`;
1467
+ text += `| Search Aggregation | 18,000 tok | 800 tok | **96%** |\n`;
1468
+ return {
1469
+ content: [
1470
+ {
1471
+ type: 'text',
1472
+ text,
1473
+ },
1474
+ ],
1475
+ };
1476
+ }
1477
+ /**
1478
+ * Run the MCP server.
1479
+ *
1480
+ * Starts the server and handles graceful shutdown.
1481
+ */
1482
+ async run() {
1483
+ const transport = new StdioServerTransport();
1484
+ // Handle graceful shutdown
1485
+ const cleanup = async () => {
1486
+ await this.cacheManager.shutdown();
1487
+ process.exit(0);
1488
+ };
1489
+ process.on('SIGINT', cleanup);
1490
+ process.on('SIGTERM', cleanup);
1491
+ await this.server.connect(transport);
1492
+ console.error('🚀 Podio MCP Server started successfully!');
1493
+ }
1494
+ }
1495
+ // Run the server if this file is executed directly
1496
+ if (import.meta.url === `file://${process.argv[1]}`) {
1497
+ // Handle command line arguments
1498
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
1499
+ console.log(`
1500
+ Podio MCP Server v0.2.0
1501
+
1502
+ A Model Context Protocol server for integrating Podio with AI assistants.
1503
+
1504
+ Usage:
1505
+ node index.js Start the MCP server
1506
+ node index.js --help, -h Show this help message
1507
+
1508
+ Environment Variables:
1509
+ PODIO_CLIENT_ID Podio app client ID (required)
1510
+ PODIO_CLIENT_SECRET Podio app client secret (required)
1511
+ PODIO_REDIRECT_URI OAuth redirect URI (required)
1512
+
1513
+ Note: App coordinates (org_label, space_label, app_label) must be provided
1514
+ explicitly in tool calls. No default app configuration is supported.
1515
+
1516
+ For more information, visit: https://github.com/podio-mcp
1517
+ `);
1518
+ process.exit(0);
1519
+ }
1520
+ const server = new PodioMCPServer();
1521
+ server.run().catch((error) => {
1522
+ console.error('❌ Server startup failed:', error);
1523
+ process.exit(1);
1524
+ });
1525
+ }
1526
+ export { PodioMCPServer };
1527
+ //# sourceMappingURL=index.js.map