cowork-os 0.3.21 → 0.3.23

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 (170) hide show
  1. package/README.md +293 -6
  2. package/connectors/README.md +20 -0
  3. package/connectors/asana-mcp/README.md +24 -0
  4. package/connectors/asana-mcp/dist/index.js +427 -0
  5. package/connectors/asana-mcp/package.json +15 -0
  6. package/connectors/asana-mcp/src/index.ts +553 -0
  7. package/connectors/asana-mcp/tsconfig.json +13 -0
  8. package/connectors/hubspot-mcp/README.md +35 -0
  9. package/connectors/hubspot-mcp/dist/index.js +454 -0
  10. package/connectors/hubspot-mcp/package.json +15 -0
  11. package/connectors/hubspot-mcp/src/index.ts +562 -0
  12. package/connectors/hubspot-mcp/tsconfig.json +13 -0
  13. package/connectors/jira-mcp/README.md +49 -0
  14. package/connectors/jira-mcp/dist/index.js +588 -0
  15. package/connectors/jira-mcp/package.json +15 -0
  16. package/connectors/jira-mcp/src/index.ts +711 -0
  17. package/connectors/jira-mcp/tsconfig.json +13 -0
  18. package/connectors/linear-mcp/README.md +22 -0
  19. package/connectors/linear-mcp/dist/index.js +402 -0
  20. package/connectors/linear-mcp/package.json +15 -0
  21. package/connectors/linear-mcp/src/index.ts +522 -0
  22. package/connectors/linear-mcp/tsconfig.json +13 -0
  23. package/connectors/okta-mcp/README.md +24 -0
  24. package/connectors/okta-mcp/dist/index.js +411 -0
  25. package/connectors/okta-mcp/package.json +15 -0
  26. package/connectors/okta-mcp/src/index.ts +520 -0
  27. package/connectors/okta-mcp/tsconfig.json +13 -0
  28. package/connectors/salesforce-mcp/README.md +47 -0
  29. package/connectors/salesforce-mcp/dist/index.js +584 -0
  30. package/connectors/salesforce-mcp/package.json +15 -0
  31. package/connectors/salesforce-mcp/src/index.ts +722 -0
  32. package/connectors/salesforce-mcp/tsconfig.json +13 -0
  33. package/connectors/servicenow-mcp/README.md +26 -0
  34. package/connectors/servicenow-mcp/dist/index.js +400 -0
  35. package/connectors/servicenow-mcp/package.json +15 -0
  36. package/connectors/servicenow-mcp/src/index.ts +500 -0
  37. package/connectors/servicenow-mcp/tsconfig.json +13 -0
  38. package/connectors/templates/mcp-connector/README.md +31 -0
  39. package/connectors/templates/mcp-connector/package.json +15 -0
  40. package/connectors/templates/mcp-connector/src/index.ts +330 -0
  41. package/connectors/templates/mcp-connector/tsconfig.json +13 -0
  42. package/connectors/zendesk-mcp/README.md +40 -0
  43. package/connectors/zendesk-mcp/dist/index.js +431 -0
  44. package/connectors/zendesk-mcp/package.json +15 -0
  45. package/connectors/zendesk-mcp/src/index.ts +543 -0
  46. package/connectors/zendesk-mcp/tsconfig.json +13 -0
  47. package/dist/electron/electron/agent/daemon.js +25 -0
  48. package/dist/electron/electron/agent/executor.js +181 -26
  49. package/dist/electron/electron/agent/llm/anthropic-compatible-provider.js +177 -0
  50. package/dist/electron/electron/agent/llm/github-copilot-provider.js +97 -0
  51. package/dist/electron/electron/agent/llm/groq-provider.js +33 -0
  52. package/dist/electron/electron/agent/llm/index.js +11 -1
  53. package/dist/electron/electron/agent/llm/kimi-provider.js +33 -0
  54. package/dist/electron/electron/agent/llm/openai-compatible-provider.js +116 -0
  55. package/dist/electron/electron/agent/llm/openai-compatible.js +111 -0
  56. package/dist/electron/electron/agent/llm/openai-oauth.js +2 -1
  57. package/dist/electron/electron/agent/llm/openrouter-provider.js +1 -1
  58. package/dist/electron/electron/agent/llm/provider-factory.js +318 -4
  59. package/dist/electron/electron/agent/llm/types.js +66 -1
  60. package/dist/electron/electron/agent/llm/xai-provider.js +33 -0
  61. package/dist/electron/electron/agent/tools/box-tools.js +231 -0
  62. package/dist/electron/electron/agent/tools/builtin-settings.js +28 -0
  63. package/dist/electron/electron/agent/tools/dropbox-tools.js +237 -0
  64. package/dist/electron/electron/agent/tools/google-drive-tools.js +227 -0
  65. package/dist/electron/electron/agent/tools/notion-tools.js +312 -0
  66. package/dist/electron/electron/agent/tools/onedrive-tools.js +217 -0
  67. package/dist/electron/electron/agent/tools/registry.js +541 -0
  68. package/dist/electron/electron/agent/tools/sharepoint-tools.js +243 -0
  69. package/dist/electron/electron/agent/tools/shell-tools.js +12 -3
  70. package/dist/electron/electron/agent/tools/x-tools.js +1 -1
  71. package/dist/electron/electron/gateway/index.js +1 -0
  72. package/dist/electron/electron/gateway/router.js +123 -143
  73. package/dist/electron/electron/ipc/canvas-handlers.js +5 -0
  74. package/dist/electron/electron/ipc/handlers.js +627 -158
  75. package/dist/electron/electron/main.js +63 -0
  76. package/dist/electron/electron/mcp/oauth/connector-oauth.js +333 -0
  77. package/dist/electron/electron/mcp/registry/MCPRegistryManager.js +503 -154
  78. package/dist/electron/electron/memory/MemoryService.js +1 -1
  79. package/dist/electron/electron/preload.js +74 -1
  80. package/dist/electron/electron/settings/box-manager.js +54 -0
  81. package/dist/electron/electron/settings/dropbox-manager.js +54 -0
  82. package/dist/electron/electron/settings/google-drive-manager.js +54 -0
  83. package/dist/electron/electron/settings/notion-manager.js +56 -0
  84. package/dist/electron/electron/settings/onedrive-manager.js +54 -0
  85. package/dist/electron/electron/settings/sharepoint-manager.js +54 -0
  86. package/dist/electron/electron/utils/box-api.js +153 -0
  87. package/dist/electron/electron/utils/dropbox-api.js +144 -0
  88. package/dist/electron/electron/utils/env-migration.js +19 -0
  89. package/dist/electron/electron/utils/google-drive-api.js +152 -0
  90. package/dist/electron/electron/utils/notion-api.js +103 -0
  91. package/dist/electron/electron/utils/onedrive-api.js +113 -0
  92. package/dist/electron/electron/utils/sharepoint-api.js +109 -0
  93. package/dist/electron/electron/utils/validation.js +82 -3
  94. package/dist/electron/electron/utils/x-cli.js +1 -1
  95. package/dist/electron/shared/channelMessages.js +284 -3
  96. package/dist/electron/shared/llm-provider-catalog.js +198 -0
  97. package/dist/electron/shared/types.js +88 -1
  98. package/package.json +12 -2
  99. package/src/electron/agent/executor.ts +205 -28
  100. package/src/electron/agent/llm/anthropic-compatible-provider.ts +214 -0
  101. package/src/electron/agent/llm/github-copilot-provider.ts +117 -0
  102. package/src/electron/agent/llm/groq-provider.ts +39 -0
  103. package/src/electron/agent/llm/index.ts +5 -0
  104. package/src/electron/agent/llm/kimi-provider.ts +39 -0
  105. package/src/electron/agent/llm/openai-compatible-provider.ts +153 -0
  106. package/src/electron/agent/llm/openai-compatible.ts +133 -0
  107. package/src/electron/agent/llm/openai-oauth.ts +2 -1
  108. package/src/electron/agent/llm/openrouter-provider.ts +2 -1
  109. package/src/electron/agent/llm/provider-factory.ts +414 -6
  110. package/src/electron/agent/llm/types.ts +90 -1
  111. package/src/electron/agent/llm/xai-provider.ts +39 -0
  112. package/src/electron/agent/tools/box-tools.ts +239 -0
  113. package/src/electron/agent/tools/builtin-settings.ts +34 -0
  114. package/src/electron/agent/tools/dropbox-tools.ts +237 -0
  115. package/src/electron/agent/tools/google-drive-tools.ts +228 -0
  116. package/src/electron/agent/tools/notion-tools.ts +330 -0
  117. package/src/electron/agent/tools/onedrive-tools.ts +217 -0
  118. package/src/electron/agent/tools/registry.ts +565 -0
  119. package/src/electron/agent/tools/sharepoint-tools.ts +247 -0
  120. package/src/electron/agent/tools/shell-tools.ts +11 -3
  121. package/src/electron/agent/tools/x-tools.ts +1 -1
  122. package/src/electron/database/SecureSettingsRepository.ts +7 -1
  123. package/src/electron/gateway/index.ts +1 -0
  124. package/src/electron/gateway/router.ts +134 -149
  125. package/src/electron/ipc/canvas-handlers.ts +10 -0
  126. package/src/electron/ipc/handlers.ts +673 -153
  127. package/src/electron/main.ts +35 -0
  128. package/src/electron/mcp/oauth/connector-oauth.ts +448 -0
  129. package/src/electron/mcp/registry/MCPRegistryManager.ts +343 -12
  130. package/src/electron/memory/MemoryService.ts +5 -1
  131. package/src/electron/preload.ts +167 -4
  132. package/src/electron/settings/box-manager.ts +58 -0
  133. package/src/electron/settings/dropbox-manager.ts +58 -0
  134. package/src/electron/settings/google-drive-manager.ts +58 -0
  135. package/src/electron/settings/notion-manager.ts +60 -0
  136. package/src/electron/settings/onedrive-manager.ts +58 -0
  137. package/src/electron/settings/sharepoint-manager.ts +58 -0
  138. package/src/electron/utils/box-api.ts +184 -0
  139. package/src/electron/utils/dropbox-api.ts +171 -0
  140. package/src/electron/utils/env-migration.ts +22 -0
  141. package/src/electron/utils/google-drive-api.ts +183 -0
  142. package/src/electron/utils/notion-api.ts +126 -0
  143. package/src/electron/utils/onedrive-api.ts +137 -0
  144. package/src/electron/utils/sharepoint-api.ts +132 -0
  145. package/src/electron/utils/validation.ts +102 -1
  146. package/src/electron/utils/x-cli.ts +1 -1
  147. package/src/renderer/App.tsx +20 -2
  148. package/src/renderer/components/BoxSettings.tsx +203 -0
  149. package/src/renderer/components/BrowserView.tsx +101 -0
  150. package/src/renderer/components/BuiltinToolsSettings.tsx +105 -0
  151. package/src/renderer/components/CanvasPreview.tsx +68 -1
  152. package/src/renderer/components/ConnectorEnvModal.tsx +116 -0
  153. package/src/renderer/components/ConnectorSetupModal.tsx +566 -0
  154. package/src/renderer/components/ConnectorsSettings.tsx +397 -0
  155. package/src/renderer/components/DropboxSettings.tsx +202 -0
  156. package/src/renderer/components/GoogleDriveSettings.tsx +201 -0
  157. package/src/renderer/components/MCPSettings.tsx +56 -0
  158. package/src/renderer/components/MainContent.tsx +270 -34
  159. package/src/renderer/components/NotionSettings.tsx +231 -0
  160. package/src/renderer/components/Onboarding/Onboarding.tsx +13 -1
  161. package/src/renderer/components/OnboardingModal.tsx +70 -1
  162. package/src/renderer/components/OneDriveSettings.tsx +212 -0
  163. package/src/renderer/components/Settings.tsx +611 -8
  164. package/src/renderer/components/SharePointSettings.tsx +224 -0
  165. package/src/renderer/components/Sidebar.tsx +25 -9
  166. package/src/renderer/hooks/useOnboardingFlow.ts +21 -0
  167. package/src/renderer/styles/index.css +438 -25
  168. package/src/shared/channelMessages.ts +367 -4
  169. package/src/shared/llm-provider-catalog.ts +217 -0
  170. package/src/shared/types.ts +226 -1
@@ -0,0 +1,711 @@
1
+ import * as readline from 'readline';
2
+
3
+ // ==================== MCP Types ====================
4
+
5
+ type JSONRPCId = string | number;
6
+
7
+ type JSONRPCRequest = {
8
+ jsonrpc: '2.0';
9
+ id: JSONRPCId;
10
+ method: string;
11
+ params?: Record<string, any>;
12
+ };
13
+
14
+ type JSONRPCNotification = {
15
+ jsonrpc: '2.0';
16
+ method: string;
17
+ params?: Record<string, any>;
18
+ };
19
+
20
+ type JSONRPCResponse = {
21
+ jsonrpc: '2.0';
22
+ id: JSONRPCId;
23
+ result?: any;
24
+ error?: { code: number; message: string; data?: any };
25
+ };
26
+
27
+ type MCPToolProperty = {
28
+ type: string;
29
+ description?: string;
30
+ enum?: string[];
31
+ default?: any;
32
+ items?: MCPToolProperty;
33
+ properties?: Record<string, MCPToolProperty>;
34
+ required?: string[];
35
+ };
36
+
37
+ type MCPTool = {
38
+ name: string;
39
+ description?: string;
40
+ inputSchema: {
41
+ type: 'object';
42
+ properties?: Record<string, MCPToolProperty>;
43
+ required?: string[];
44
+ additionalProperties?: boolean;
45
+ };
46
+ };
47
+
48
+ type MCPServerInfo = {
49
+ name: string;
50
+ version: string;
51
+ protocolVersion?: string;
52
+ capabilities?: {
53
+ tools?: { listChanged?: boolean };
54
+ };
55
+ };
56
+
57
+ const PROTOCOL_VERSION = '2024-11-05';
58
+
59
+ const MCP_METHODS = {
60
+ INITIALIZE: 'initialize',
61
+ INITIALIZED: 'notifications/initialized',
62
+ SHUTDOWN: 'shutdown',
63
+ TOOLS_LIST: 'tools/list',
64
+ TOOLS_CALL: 'tools/call',
65
+ } as const;
66
+
67
+ const MCP_ERROR_CODES = {
68
+ PARSE_ERROR: -32700,
69
+ INVALID_REQUEST: -32600,
70
+ METHOD_NOT_FOUND: -32601,
71
+ INVALID_PARAMS: -32602,
72
+ INTERNAL_ERROR: -32603,
73
+ SERVER_NOT_INITIALIZED: -32002,
74
+ } as const;
75
+
76
+ // ==================== Jira Client ====================
77
+
78
+ type JiraConfig = {
79
+ baseUrl?: string;
80
+ apiVersion: string;
81
+ accessToken?: string;
82
+ email?: string;
83
+ apiToken?: string;
84
+ clientId?: string;
85
+ clientSecret?: string;
86
+ refreshToken?: string;
87
+ };
88
+
89
+ type RateLimitInfo = {
90
+ limit: number;
91
+ remaining: number;
92
+ resetAt?: string;
93
+ };
94
+
95
+ type RequestMeta = {
96
+ durationMs: number;
97
+ rateLimit?: RateLimitInfo;
98
+ vendorRequestId?: string;
99
+ apiVersion: string;
100
+ baseUrl?: string;
101
+ };
102
+
103
+ type RequestResult = {
104
+ data: any;
105
+ meta: RequestMeta;
106
+ nextCursor?: string;
107
+ };
108
+
109
+ class JiraClient {
110
+ private config: JiraConfig;
111
+
112
+ constructor(config: JiraConfig) {
113
+ this.config = config;
114
+ }
115
+
116
+ async health(): Promise<RequestResult> {
117
+ return this.requestJson('GET', 'myself');
118
+ }
119
+
120
+ async listProjects(startAt?: number, maxResults?: number): Promise<RequestResult> {
121
+ const params = new URLSearchParams();
122
+ if (startAt !== undefined) params.set('startAt', String(startAt));
123
+ if (maxResults !== undefined) params.set('maxResults', String(maxResults));
124
+ const query = params.toString();
125
+ return this.requestJson('GET', `project/search${query ? `?${query}` : ''}`);
126
+ }
127
+
128
+ async getIssue(issueIdOrKey: string, fields?: string[]): Promise<RequestResult> {
129
+ const params = new URLSearchParams();
130
+ if (fields && fields.length > 0) params.set('fields', fields.join(','));
131
+ const query = params.toString();
132
+ return this.requestJson('GET', `issue/${encodeURIComponent(issueIdOrKey)}${query ? `?${query}` : ''}`);
133
+ }
134
+
135
+ async searchIssues(jql: string, startAt?: number, maxResults?: number, fields?: string[]): Promise<RequestResult> {
136
+ const payload: Record<string, any> = { jql };
137
+ if (startAt !== undefined) payload.startAt = startAt;
138
+ if (maxResults !== undefined) payload.maxResults = maxResults;
139
+ if (fields && fields.length > 0) payload.fields = fields;
140
+ return this.requestJson('POST', 'search', payload);
141
+ }
142
+
143
+ async createIssue(payload: Record<string, any>): Promise<RequestResult> {
144
+ return this.requestJson('POST', 'issue', payload);
145
+ }
146
+
147
+ async updateIssue(issueIdOrKey: string, payload: Record<string, any>): Promise<RequestResult> {
148
+ return this.requestJson('PUT', `issue/${encodeURIComponent(issueIdOrKey)}`, payload);
149
+ }
150
+
151
+ private getBaseUrl(): string {
152
+ if (!this.config.baseUrl) {
153
+ throw new Error('JIRA_BASE_URL is required');
154
+ }
155
+ return `${this.config.baseUrl.replace(/\/$/, '')}/rest/api/${this.config.apiVersion}`;
156
+ }
157
+
158
+ private canRefresh(): boolean {
159
+ return Boolean(this.config.clientId && this.config.clientSecret && this.config.refreshToken);
160
+ }
161
+
162
+ private async ensureAccessToken(): Promise<string> {
163
+ if (this.config.accessToken) {
164
+ return this.config.accessToken;
165
+ }
166
+ if (!this.canRefresh()) {
167
+ throw new Error('Missing Jira credentials (provide JIRA_ACCESS_TOKEN or JIRA_EMAIL + JIRA_API_TOKEN)');
168
+ }
169
+ await this.refreshAccessToken();
170
+ if (!this.config.accessToken) {
171
+ throw new Error('Failed to refresh Jira access token');
172
+ }
173
+ return this.config.accessToken;
174
+ }
175
+
176
+ private async getAuthHeader(): Promise<string> {
177
+ if (this.config.accessToken || this.canRefresh()) {
178
+ const token = await this.ensureAccessToken();
179
+ return `Bearer ${token}`;
180
+ }
181
+ if (this.config.email && this.config.apiToken) {
182
+ const basic = Buffer.from(`${this.config.email}:${this.config.apiToken}`).toString('base64');
183
+ return `Basic ${basic}`;
184
+ }
185
+ throw new Error('Missing Jira credentials (provide JIRA_ACCESS_TOKEN or JIRA_EMAIL + JIRA_API_TOKEN)');
186
+ }
187
+
188
+ private async requestJson(method: string, path: string, body?: any): Promise<RequestResult> {
189
+ const start = Date.now();
190
+ const url = `${this.getBaseUrl()}/${path.replace(/^\//, '')}`;
191
+ const res = await fetch(url, {
192
+ method,
193
+ headers: {
194
+ Authorization: await this.getAuthHeader(),
195
+ 'Content-Type': 'application/json',
196
+ 'User-Agent': 'CoWork-Jira-Connector/0.1.0',
197
+ },
198
+ body: body ? JSON.stringify(body) : undefined,
199
+ });
200
+
201
+ const durationMs = Date.now() - start;
202
+ const rateLimit = parseRateLimit(res.headers);
203
+ const vendorRequestId = res.headers.get('x-arequestid') || res.headers.get('x-request-id') || undefined;
204
+
205
+ if (res.status === 401 && this.canRefresh()) {
206
+ await this.refreshAccessToken();
207
+ return this.requestJson(method, path, body);
208
+ }
209
+
210
+ if (!res.ok) {
211
+ const message = await this.extractErrorMessage(res);
212
+ throw new Error(message);
213
+ }
214
+
215
+ let data: any = null;
216
+ if (res.status !== 204) {
217
+ data = await res.json();
218
+ }
219
+
220
+ const nextCursor = deriveNextCursor(data);
221
+
222
+ return {
223
+ data,
224
+ meta: {
225
+ durationMs,
226
+ rateLimit,
227
+ vendorRequestId,
228
+ apiVersion: this.config.apiVersion,
229
+ baseUrl: this.config.baseUrl,
230
+ },
231
+ nextCursor,
232
+ };
233
+ }
234
+
235
+ private async refreshAccessToken(): Promise<void> {
236
+ if (!this.canRefresh()) {
237
+ throw new Error('Missing Jira refresh credentials');
238
+ }
239
+
240
+ const res = await fetch('https://auth.atlassian.com/oauth/token', {
241
+ method: 'POST',
242
+ headers: { 'Content-Type': 'application/json' },
243
+ body: JSON.stringify({
244
+ grant_type: 'refresh_token',
245
+ client_id: this.config.clientId,
246
+ client_secret: this.config.clientSecret,
247
+ refresh_token: this.config.refreshToken,
248
+ }),
249
+ });
250
+
251
+ if (!res.ok) {
252
+ const text = await res.text();
253
+ throw new Error(`Jira OAuth refresh failed: ${text}`);
254
+ }
255
+
256
+ const data = await res.json();
257
+ if (!data.access_token) {
258
+ throw new Error('Jira OAuth refresh returned no access_token');
259
+ }
260
+
261
+ this.config.accessToken = data.access_token;
262
+ }
263
+
264
+ private async extractErrorMessage(res: Response): Promise<string> {
265
+ const text = await res.text();
266
+ if (!text) {
267
+ return `Jira API error (status ${res.status})`;
268
+ }
269
+
270
+ try {
271
+ const parsed = JSON.parse(text);
272
+ if (parsed.errorMessages && Array.isArray(parsed.errorMessages) && parsed.errorMessages.length > 0) {
273
+ return parsed.errorMessages.join('; ');
274
+ }
275
+ if (parsed.errors && typeof parsed.errors === 'object') {
276
+ const messages = Object.entries(parsed.errors).map(([field, msg]) => `${field}: ${msg}`);
277
+ return messages.join('; ');
278
+ }
279
+ if (parsed.message) {
280
+ return parsed.message;
281
+ }
282
+ return JSON.stringify(parsed);
283
+ } catch {
284
+ return text;
285
+ }
286
+ }
287
+ }
288
+
289
+ function parseRateLimit(headers: Headers): RateLimitInfo | undefined {
290
+ const limit = numberHeader(headers.get('x-ratelimit-limit'));
291
+ const remaining = numberHeader(headers.get('x-ratelimit-remaining'));
292
+ const reset = headers.get('x-ratelimit-reset');
293
+ if (limit === undefined || remaining === undefined) {
294
+ return undefined;
295
+ }
296
+ return {
297
+ limit,
298
+ remaining,
299
+ resetAt: reset || undefined,
300
+ };
301
+ }
302
+
303
+ function numberHeader(value: string | null): number | undefined {
304
+ if (!value) return undefined;
305
+ const num = Number(value);
306
+ return Number.isFinite(num) ? num : undefined;
307
+ }
308
+
309
+ function deriveNextCursor(data: any): string | undefined {
310
+ if (!data || typeof data !== 'object') return undefined;
311
+ if (typeof data.startAt === 'number' && typeof data.maxResults === 'number' && typeof data.total === 'number') {
312
+ const next = data.startAt + data.maxResults;
313
+ if (next < data.total) {
314
+ return String(next);
315
+ }
316
+ }
317
+ return undefined;
318
+ }
319
+
320
+ // ==================== MCP Stdio Server ====================
321
+
322
+ type ToolProvider = {
323
+ getTools(): MCPTool[];
324
+ executeTool(name: string, args: Record<string, any>): Promise<any>;
325
+ };
326
+
327
+ class StdioMCPServer {
328
+ private initialized = false;
329
+ private rl: readline.Interface | null = null;
330
+
331
+ constructor(
332
+ private toolProvider: ToolProvider,
333
+ private serverInfo: MCPServerInfo
334
+ ) {}
335
+
336
+ start(): void {
337
+ this.rl = readline.createInterface({
338
+ input: process.stdin,
339
+ output: process.stdout,
340
+ terminal: false,
341
+ });
342
+
343
+ this.rl.on('line', (line) => this.handleLine(line));
344
+ this.rl.on('close', () => this.stop());
345
+
346
+ process.on('SIGINT', () => this.stop());
347
+ process.on('SIGTERM', () => this.stop());
348
+ }
349
+
350
+ stop(): void {
351
+ if (this.rl) {
352
+ this.rl.close();
353
+ this.rl = null;
354
+ }
355
+ process.exit(0);
356
+ }
357
+
358
+ private handleLine(line: string): void {
359
+ const trimmed = line.trim();
360
+ if (!trimmed) return;
361
+
362
+ try {
363
+ const message = JSON.parse(trimmed);
364
+ this.handleMessage(message);
365
+ } catch (error) {
366
+ this.sendError(0, MCP_ERROR_CODES.PARSE_ERROR, 'Parse error');
367
+ }
368
+ }
369
+
370
+ private async handleMessage(message: any): Promise<void> {
371
+ if ('id' in message && message.id !== null) {
372
+ await this.handleRequest(message as JSONRPCRequest);
373
+ return;
374
+ }
375
+
376
+ if ('method' in message) {
377
+ await this.handleNotification(message as JSONRPCNotification);
378
+ }
379
+ }
380
+
381
+ private async handleRequest(request: JSONRPCRequest): Promise<void> {
382
+ const { id, method, params } = request;
383
+
384
+ try {
385
+ let result: any;
386
+
387
+ switch (method) {
388
+ case MCP_METHODS.INITIALIZE:
389
+ result = this.handleInitialize(params);
390
+ break;
391
+ case MCP_METHODS.TOOLS_LIST:
392
+ this.requireInitialized();
393
+ result = this.handleToolsList();
394
+ break;
395
+ case MCP_METHODS.TOOLS_CALL:
396
+ this.requireInitialized();
397
+ result = await this.handleToolsCall(params);
398
+ break;
399
+ case MCP_METHODS.SHUTDOWN:
400
+ result = this.handleShutdown();
401
+ break;
402
+ default:
403
+ throw this.createError(MCP_ERROR_CODES.METHOD_NOT_FOUND, `Method not found: ${method}`);
404
+ }
405
+
406
+ this.sendResult(id, result);
407
+ } catch (error: any) {
408
+ if (error.code !== undefined) {
409
+ this.sendError(id, error.code, error.message, error.data);
410
+ } else {
411
+ this.sendError(id, MCP_ERROR_CODES.INTERNAL_ERROR, error?.message || 'Internal error');
412
+ }
413
+ }
414
+ }
415
+
416
+ private async handleNotification(notification: JSONRPCNotification): Promise<void> {
417
+ const { method } = notification;
418
+
419
+ if (method === MCP_METHODS.INITIALIZED) {
420
+ this.initialized = true;
421
+ }
422
+ }
423
+
424
+ private handleInitialize(_params: any): {
425
+ protocolVersion: string;
426
+ capabilities: MCPServerInfo['capabilities'];
427
+ serverInfo: MCPServerInfo;
428
+ } {
429
+ if (this.initialized) {
430
+ throw this.createError(MCP_ERROR_CODES.INVALID_REQUEST, 'Already initialized');
431
+ }
432
+
433
+ return {
434
+ protocolVersion: PROTOCOL_VERSION,
435
+ capabilities: this.serverInfo.capabilities,
436
+ serverInfo: this.serverInfo,
437
+ };
438
+ }
439
+
440
+ private handleToolsList(): { tools: MCPTool[] } {
441
+ return { tools: this.toolProvider.getTools() };
442
+ }
443
+
444
+ private async handleToolsCall(params: any): Promise<any> {
445
+ const { name, arguments: args } = params || {};
446
+ if (!name) {
447
+ throw this.createError(MCP_ERROR_CODES.INVALID_PARAMS, 'Tool name is required');
448
+ }
449
+
450
+ try {
451
+ const result = await this.toolProvider.executeTool(name, args || {});
452
+
453
+ if (typeof result === 'string') {
454
+ return { content: [{ type: 'text', text: result }] };
455
+ }
456
+
457
+ if (result && typeof result === 'object') {
458
+ if (result.content && Array.isArray(result.content)) {
459
+ return result;
460
+ }
461
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
462
+ }
463
+
464
+ return { content: [{ type: 'text', text: String(result) }] };
465
+ } catch (error: any) {
466
+ return {
467
+ content: [{ type: 'text', text: `Error: ${error?.message || 'Tool failed'}` }],
468
+ isError: true,
469
+ };
470
+ }
471
+ }
472
+
473
+ private handleShutdown(): Record<string, never> {
474
+ setImmediate(() => this.stop());
475
+ return {};
476
+ }
477
+
478
+ private sendResult(id: JSONRPCId, result: any): void {
479
+ const response: JSONRPCResponse = { jsonrpc: '2.0', id, result };
480
+ this.sendMessage(response);
481
+ }
482
+
483
+ private sendError(id: JSONRPCId, code: number, message: string, data?: any): void {
484
+ const response: JSONRPCResponse = {
485
+ jsonrpc: '2.0',
486
+ id,
487
+ error: { code, message, data },
488
+ };
489
+ this.sendMessage(response);
490
+ }
491
+
492
+ private sendMessage(message: JSONRPCResponse | JSONRPCNotification): void {
493
+ process.stdout.write(JSON.stringify(message) + '\n');
494
+ }
495
+
496
+ private requireInitialized(): void {
497
+ if (!this.initialized) {
498
+ throw this.createError(MCP_ERROR_CODES.SERVER_NOT_INITIALIZED, 'Server not initialized');
499
+ }
500
+ }
501
+
502
+ private createError(code: number, message: string, data?: any): { code: number; message: string; data?: any } {
503
+ return { code, message, data };
504
+ }
505
+ }
506
+
507
+ // ==================== Tool Definitions ====================
508
+
509
+ const CONNECTOR_PREFIX = 'jira';
510
+ const DEFAULT_API_VERSION = '3';
511
+
512
+ const tools: MCPTool[] = [
513
+ {
514
+ name: `${CONNECTOR_PREFIX}.health`,
515
+ description: 'Check connector health and authentication status',
516
+ inputSchema: {
517
+ type: 'object',
518
+ properties: {
519
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
520
+ },
521
+ additionalProperties: false,
522
+ },
523
+ },
524
+ {
525
+ name: `${CONNECTOR_PREFIX}.list_projects`,
526
+ description: 'List Jira projects',
527
+ inputSchema: {
528
+ type: 'object',
529
+ properties: {
530
+ limit: { type: 'number', description: 'Max results per page' },
531
+ cursor: { type: 'string', description: 'Pagination cursor (startAt number)' },
532
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
533
+ },
534
+ additionalProperties: false,
535
+ },
536
+ },
537
+ {
538
+ name: `${CONNECTOR_PREFIX}.get_issue`,
539
+ description: 'Fetch a Jira issue by id or key',
540
+ inputSchema: {
541
+ type: 'object',
542
+ properties: {
543
+ id: { type: 'string', description: 'Issue id or key (e.g., PROJ-123)' },
544
+ fields: {
545
+ type: 'array',
546
+ description: 'Optional list of fields to include',
547
+ items: { type: 'string' },
548
+ },
549
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
550
+ },
551
+ required: ['id'],
552
+ additionalProperties: false,
553
+ },
554
+ },
555
+ {
556
+ name: `${CONNECTOR_PREFIX}.search_issues`,
557
+ description: 'Run a JQL query',
558
+ inputSchema: {
559
+ type: 'object',
560
+ properties: {
561
+ jql: { type: 'string', description: 'JQL query to execute' },
562
+ fields: {
563
+ type: 'array',
564
+ description: 'Optional list of fields to include',
565
+ items: { type: 'string' },
566
+ },
567
+ limit: { type: 'number', description: 'Max results per page' },
568
+ cursor: { type: 'string', description: 'Pagination cursor (startAt number)' },
569
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
570
+ },
571
+ required: ['jql'],
572
+ additionalProperties: false,
573
+ },
574
+ },
575
+ {
576
+ name: `${CONNECTOR_PREFIX}.create_issue`,
577
+ description: 'Create a Jira issue',
578
+ inputSchema: {
579
+ type: 'object',
580
+ properties: {
581
+ projectKey: { type: 'string', description: 'Project key (e.g., PROJ)' },
582
+ issueType: { type: 'string', description: 'Issue type (e.g., Task, Bug)' },
583
+ fields: { type: 'object', description: 'Additional Jira fields to include' },
584
+ idempotencyKey: { type: 'string', description: 'Optional idempotency key (best-effort)' },
585
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
586
+ },
587
+ required: ['projectKey', 'issueType', 'fields'],
588
+ additionalProperties: false,
589
+ },
590
+ },
591
+ {
592
+ name: `${CONNECTOR_PREFIX}.update_issue`,
593
+ description: 'Update a Jira issue',
594
+ inputSchema: {
595
+ type: 'object',
596
+ properties: {
597
+ id: { type: 'string', description: 'Issue id or key (e.g., PROJ-123)' },
598
+ fields: { type: 'object', description: 'Field map for update' },
599
+ idempotencyKey: { type: 'string', description: 'Optional idempotency key (best-effort)' },
600
+ requestId: { type: 'string', description: 'Optional request id for tracing' },
601
+ },
602
+ required: ['id', 'fields'],
603
+ additionalProperties: false,
604
+ },
605
+ },
606
+ ];
607
+
608
+ const config: JiraConfig = {
609
+ baseUrl: process.env.JIRA_BASE_URL,
610
+ apiVersion: process.env.JIRA_API_VERSION || DEFAULT_API_VERSION,
611
+ accessToken: process.env.JIRA_ACCESS_TOKEN,
612
+ email: process.env.JIRA_EMAIL,
613
+ apiToken: process.env.JIRA_API_TOKEN,
614
+ clientId: process.env.JIRA_CLIENT_ID,
615
+ clientSecret: process.env.JIRA_CLIENT_SECRET,
616
+ refreshToken: process.env.JIRA_REFRESH_TOKEN,
617
+ };
618
+
619
+ const client = new JiraClient(config);
620
+
621
+ const handlers: Record<string, (args: Record<string, any>) => Promise<any>> = {
622
+ [`${CONNECTOR_PREFIX}.health`]: async (args) => {
623
+ const result = await client.health();
624
+ return buildEnvelope(result, args.requestId);
625
+ },
626
+ [`${CONNECTOR_PREFIX}.list_projects`]: async (args) => {
627
+ const startAt = parseCursor(args.cursor);
628
+ const result = await client.listProjects(startAt, args.limit);
629
+ return buildEnvelope(result, args.requestId);
630
+ },
631
+ [`${CONNECTOR_PREFIX}.get_issue`]: async (args) => {
632
+ const result = await client.getIssue(args.id, args.fields);
633
+ return buildEnvelope(result, args.requestId);
634
+ },
635
+ [`${CONNECTOR_PREFIX}.search_issues`]: async (args) => {
636
+ const startAt = parseCursor(args.cursor);
637
+ const result = await client.searchIssues(args.jql, startAt, args.limit, args.fields);
638
+ return buildEnvelope(result, args.requestId);
639
+ },
640
+ [`${CONNECTOR_PREFIX}.create_issue`]: async (args) => {
641
+ const payload = buildCreatePayload(args.projectKey, args.issueType, args.fields);
642
+ const warnings = args.idempotencyKey
643
+ ? ['Jira does not natively support idempotency keys; handled best-effort.']
644
+ : [];
645
+ const result = await client.createIssue(payload);
646
+ return buildEnvelope(result, args.requestId, warnings);
647
+ },
648
+ [`${CONNECTOR_PREFIX}.update_issue`]: async (args) => {
649
+ const warnings = args.idempotencyKey
650
+ ? ['Jira does not natively support idempotency keys; handled best-effort.']
651
+ : [];
652
+ const result = await client.updateIssue(args.id, { fields: args.fields });
653
+ return buildEnvelope(result, args.requestId, warnings);
654
+ },
655
+ };
656
+
657
+ const toolProvider: ToolProvider = {
658
+ getTools: () => tools,
659
+ executeTool: async (name, args) => {
660
+ const handler = handlers[name];
661
+ if (!handler) {
662
+ throw new Error(`Unknown tool: ${name}`);
663
+ }
664
+ return handler(args);
665
+ },
666
+ };
667
+
668
+ const serverInfo: MCPServerInfo = {
669
+ name: 'Jira Connector',
670
+ version: '0.1.0',
671
+ protocolVersion: PROTOCOL_VERSION,
672
+ capabilities: {
673
+ tools: { listChanged: false },
674
+ },
675
+ };
676
+
677
+ const server = new StdioMCPServer(toolProvider, serverInfo);
678
+ server.start();
679
+
680
+ function buildEnvelope(result: RequestResult, requestId?: string, warnings: string[] = []): any {
681
+ return {
682
+ ok: true,
683
+ data: result.data,
684
+ meta: {
685
+ requestId,
686
+ durationMs: result.meta.durationMs,
687
+ rateLimit: result.meta.rateLimit,
688
+ vendorRequestId: result.meta.vendorRequestId,
689
+ apiVersion: result.meta.apiVersion,
690
+ baseUrl: result.meta.baseUrl,
691
+ },
692
+ nextCursor: result.nextCursor,
693
+ warnings,
694
+ };
695
+ }
696
+
697
+ function parseCursor(cursor?: string): number | undefined {
698
+ if (!cursor) return undefined;
699
+ const value = Number(cursor);
700
+ return Number.isFinite(value) ? value : undefined;
701
+ }
702
+
703
+ function buildCreatePayload(projectKey: string, issueType: string, fields: Record<string, any>): Record<string, any> {
704
+ return {
705
+ fields: {
706
+ ...fields,
707
+ project: { key: projectKey },
708
+ issuetype: { name: issueType },
709
+ },
710
+ };
711
+ }