@gethmy/mcp 1.0.0 → 2.1.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 (65) hide show
  1. package/README.md +201 -36
  2. package/dist/cli.js +20938 -20249
  3. package/dist/http.js +1957 -0
  4. package/dist/index.js +17833 -17888
  5. package/dist/lib/__tests__/active-learning.test.js +386 -0
  6. package/dist/lib/__tests__/agent-performance-profiles.test.js +325 -0
  7. package/dist/lib/__tests__/auto-session.test.js +661 -0
  8. package/dist/lib/__tests__/context-assembly.test.js +362 -0
  9. package/dist/lib/__tests__/graph-expansion.test.js +150 -0
  10. package/dist/lib/__tests__/integration-memory-crud.test.js +797 -0
  11. package/dist/lib/__tests__/integration-memory-system.test.js +281 -0
  12. package/dist/lib/__tests__/lifecycle-maintenance.test.js +207 -0
  13. package/dist/lib/__tests__/pattern-detection.test.js +295 -0
  14. package/dist/lib/__tests__/prompt-builder.test.js +418 -0
  15. package/dist/lib/active-learning.js +878 -0
  16. package/dist/lib/api-client.js +548 -0
  17. package/dist/lib/auto-session.js +173 -0
  18. package/dist/lib/cli.js +127 -0
  19. package/dist/lib/config.js +205 -0
  20. package/dist/lib/consolidation.js +243 -0
  21. package/dist/lib/context-assembly.js +606 -0
  22. package/dist/lib/graph-expansion.js +163 -0
  23. package/dist/lib/http.js +174 -0
  24. package/dist/lib/index.js +7 -0
  25. package/dist/lib/lifecycle-maintenance.js +88 -0
  26. package/dist/lib/prompt-builder.js +483 -0
  27. package/dist/lib/remote.js +166 -0
  28. package/dist/lib/server.js +3132 -0
  29. package/dist/lib/tui/agents.js +116 -0
  30. package/dist/lib/tui/docs.js +558 -0
  31. package/dist/lib/tui/setup.js +1068 -0
  32. package/dist/lib/tui/theme.js +95 -0
  33. package/dist/lib/tui/writer.js +200 -0
  34. package/dist/remote.js +34534 -0
  35. package/dist/server.js +31967 -0
  36. package/package.json +20 -7
  37. package/src/__tests__/active-learning.test.ts +483 -0
  38. package/src/__tests__/agent-performance-profiles.test.ts +468 -0
  39. package/src/__tests__/auto-session.test.ts +912 -0
  40. package/src/__tests__/context-assembly.test.ts +506 -0
  41. package/src/__tests__/graph-expansion.test.ts +285 -0
  42. package/src/__tests__/integration-memory-crud.test.ts +948 -0
  43. package/src/__tests__/integration-memory-system.test.ts +321 -0
  44. package/src/__tests__/lifecycle-maintenance.test.ts +238 -0
  45. package/src/__tests__/pattern-detection.test.ts +438 -0
  46. package/src/__tests__/prompt-builder.test.ts +505 -0
  47. package/src/active-learning.ts +1227 -0
  48. package/src/api-client.ts +963 -0
  49. package/src/auto-session.ts +218 -0
  50. package/src/cli.ts +166 -0
  51. package/src/config.ts +285 -0
  52. package/src/consolidation.ts +314 -0
  53. package/src/context-assembly.ts +842 -0
  54. package/src/graph-expansion.ts +234 -0
  55. package/src/http.ts +265 -0
  56. package/src/index.ts +8 -0
  57. package/src/lifecycle-maintenance.ts +120 -0
  58. package/src/prompt-builder.ts +681 -0
  59. package/src/remote.ts +227 -0
  60. package/src/server.ts +3858 -0
  61. package/src/tui/agents.ts +154 -0
  62. package/src/tui/docs.ts +650 -0
  63. package/src/tui/setup.ts +1281 -0
  64. package/src/tui/theme.ts +114 -0
  65. package/src/tui/writer.ts +260 -0
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Prompt Builder for Harmony MCP Server
3
+ *
4
+ * Generates AI-ready prompts from Harmony cards with role-based framing,
5
+ * context extraction, and variant-specific instructions.
6
+ */
7
+ // Label name to category mapping
8
+ const LABEL_CATEGORY_MAP = {
9
+ bug: "bug",
10
+ fix: "bug",
11
+ hotfix: "bug",
12
+ defect: "bug",
13
+ issue: "bug",
14
+ error: "bug",
15
+ feature: "feature",
16
+ enhancement: "feature",
17
+ improvement: "feature",
18
+ new: "feature",
19
+ design: "design",
20
+ ui: "design",
21
+ ux: "design",
22
+ frontend: "design",
23
+ styling: "design",
24
+ review: "review",
25
+ "code review": "review",
26
+ pr: "review",
27
+ feedback: "review",
28
+ onboarding: "onboarding",
29
+ documentation: "onboarding",
30
+ docs: "onboarding",
31
+ guide: "onboarding",
32
+ tutorial: "onboarding",
33
+ epic: "epic",
34
+ initiative: "epic",
35
+ project: "epic",
36
+ milestone: "epic",
37
+ };
38
+ // Default role framings
39
+ const DEFAULT_ROLE_FRAMINGS = {
40
+ bug: {
41
+ category: "bug",
42
+ role: "Senior QA Engineer and Software Developer",
43
+ perspective: "You are investigating and fixing a bug report.",
44
+ focus: [
45
+ "Root cause analysis",
46
+ "Steps to reproduce",
47
+ "Impact assessment",
48
+ "Fix implementation",
49
+ "Regression prevention",
50
+ "Test cases to prevent recurrence",
51
+ ],
52
+ outputSuggestions: [
53
+ "Bug triage summary",
54
+ "Root cause explanation",
55
+ "Fix implementation plan",
56
+ "Test cases",
57
+ ],
58
+ },
59
+ feature: {
60
+ category: "feature",
61
+ role: "Product Engineer",
62
+ perspective: "You are implementing a new feature or enhancement.",
63
+ focus: [
64
+ "User requirements",
65
+ "Technical specification",
66
+ "Implementation approach",
67
+ "Edge cases",
68
+ "Acceptance criteria",
69
+ "Integration points",
70
+ ],
71
+ outputSuggestions: [
72
+ "Technical specification",
73
+ "Implementation tasks",
74
+ "Acceptance criteria checklist",
75
+ "API design",
76
+ ],
77
+ },
78
+ design: {
79
+ category: "design",
80
+ role: "UX Designer and Frontend Developer",
81
+ perspective: "You are designing and implementing a user interface.",
82
+ focus: [
83
+ "User experience flow",
84
+ "Visual design consistency",
85
+ "Accessibility (WCAG)",
86
+ "Responsive behavior",
87
+ "Component architecture",
88
+ "Interaction patterns",
89
+ ],
90
+ outputSuggestions: [
91
+ "User flow diagram",
92
+ "Component specifications",
93
+ "Accessibility checklist",
94
+ "Responsive breakpoints",
95
+ ],
96
+ },
97
+ review: {
98
+ category: "review",
99
+ role: "Code Reviewer and Technical Lead",
100
+ perspective: "You are reviewing code for quality, correctness, and maintainability.",
101
+ focus: [
102
+ "Code correctness",
103
+ "Performance implications",
104
+ "Security considerations",
105
+ "Testing coverage",
106
+ "Documentation",
107
+ "Best practices adherence",
108
+ ],
109
+ outputSuggestions: [
110
+ "Review checklist",
111
+ "Suggested improvements",
112
+ "Test scenarios",
113
+ "Security audit",
114
+ ],
115
+ },
116
+ onboarding: {
117
+ category: "onboarding",
118
+ role: "Technical Writer and Developer Advocate",
119
+ perspective: "You are creating documentation or onboarding materials.",
120
+ focus: [
121
+ "Clear step-by-step instructions",
122
+ "Prerequisites and setup",
123
+ "Common pitfalls",
124
+ "Examples and use cases",
125
+ "Troubleshooting guide",
126
+ "Related resources",
127
+ ],
128
+ outputSuggestions: [
129
+ "Getting started guide",
130
+ "Step-by-step tutorial",
131
+ "FAQ section",
132
+ "Troubleshooting guide",
133
+ ],
134
+ },
135
+ epic: {
136
+ category: "epic",
137
+ role: "Technical Project Manager and Architect",
138
+ perspective: "You are planning and coordinating a large initiative.",
139
+ focus: [
140
+ "Scope definition",
141
+ "Task breakdown",
142
+ "Dependencies",
143
+ "Risk assessment",
144
+ "Timeline considerations",
145
+ "Success metrics",
146
+ ],
147
+ outputSuggestions: [
148
+ "Epic breakdown into stories",
149
+ "Dependency graph",
150
+ "Risk mitigation plan",
151
+ "Success criteria",
152
+ ],
153
+ },
154
+ custom: {
155
+ category: "custom",
156
+ role: "Software Engineer",
157
+ perspective: "You are working on a software task.",
158
+ focus: [
159
+ "Understanding requirements",
160
+ "Implementation approach",
161
+ "Quality considerations",
162
+ "Testing strategy",
163
+ ],
164
+ outputSuggestions: [
165
+ "Implementation plan",
166
+ "Technical notes",
167
+ "Task checklist",
168
+ ],
169
+ },
170
+ };
171
+ // Variant-specific instructions
172
+ const VARIANT_INSTRUCTIONS = {
173
+ analysis: `ANALYSIS MODE: Analyze this task thoroughly. Identify requirements, constraints, edge cases, and potential challenges. Do NOT implement anything yet - focus on understanding and planning.`,
174
+ draft: `DRAFT MODE: Create a detailed implementation plan with code structure, key decisions, and approach. Include pseudocode or skeleton code where helpful. This is for review before full implementation.`,
175
+ execute: `EXECUTE MODE: Implement this task completely. Write production-ready code following best practices. Include necessary tests and documentation.`,
176
+ };
177
+ /**
178
+ * Infer category from labels
179
+ */
180
+ export function inferCategoryFromLabels(labels) {
181
+ for (const label of labels) {
182
+ const normalizedName = label.name.toLowerCase().trim();
183
+ if (LABEL_CATEGORY_MAP[normalizedName]) {
184
+ return LABEL_CATEGORY_MAP[normalizedName];
185
+ }
186
+ for (const [key, category] of Object.entries(LABEL_CATEGORY_MAP)) {
187
+ if (normalizedName.includes(key) || key.includes(normalizedName)) {
188
+ return category;
189
+ }
190
+ }
191
+ }
192
+ return "custom";
193
+ }
194
+ /**
195
+ * Get role framing for a category
196
+ */
197
+ export function getRoleFraming(category) {
198
+ return DEFAULT_ROLE_FRAMINGS[category];
199
+ }
200
+ /**
201
+ * Estimate token count (rough approximation: 1 token per 4 chars)
202
+ */
203
+ function estimateTokens(text) {
204
+ return Math.ceil(text.length / 4);
205
+ }
206
+ /**
207
+ * Format subtasks for prompt
208
+ */
209
+ function formatSubtasks(subtasks) {
210
+ if (subtasks.length === 0)
211
+ return "";
212
+ const completed = subtasks.filter((s) => s.completed).length;
213
+ const lines = subtasks.map((s) => ` ${s.completed ? "[x]" : "[ ]"} ${s.title}`);
214
+ return `\n## Subtasks (${completed}/${subtasks.length} completed)\n${lines.join("\n")}`;
215
+ }
216
+ /**
217
+ * Format labels for prompt
218
+ */
219
+ function formatLabels(labels) {
220
+ if (labels.length === 0)
221
+ return "";
222
+ return `\n**Labels:** ${labels.map((l) => l.name).join(", ")}`;
223
+ }
224
+ /**
225
+ * Format linked cards for prompt
226
+ */
227
+ function formatLinkedCards(links) {
228
+ if (!links || links.length === 0)
229
+ return "";
230
+ const lines = links.map((link) => {
231
+ const prefix = link.direction === "outgoing" ? "->" : "<-";
232
+ return ` ${prefix} #${link.target_card.short_id}: ${link.target_card.title} (${link.display_type})`;
233
+ });
234
+ return `\n## Related Cards\n${lines.join("\n")}`;
235
+ }
236
+ /**
237
+ * Generate a prompt from a card
238
+ */
239
+ export function generatePrompt(options) {
240
+ const { card, column, variant, customConstraints, memories, assembledContext, assemblyId, } = options;
241
+ // Merge context options with defaults
242
+ const contextOpts = {
243
+ includeTitle: true,
244
+ includeDescription: true,
245
+ includeLabels: true,
246
+ includeSubtasks: true,
247
+ includeActivity: false,
248
+ includeAssignee: true,
249
+ includeDueDate: true,
250
+ includePriority: true,
251
+ includeLinks: true,
252
+ includeColumn: true,
253
+ ...options.contextOptions,
254
+ };
255
+ const labels = card.labels || [];
256
+ const subtasks = card.subtasks || [];
257
+ const links = card.links || [];
258
+ const category = inferCategoryFromLabels(labels);
259
+ const roleFraming = getRoleFraming(category);
260
+ // Build prompt sections
261
+ const sections = [];
262
+ // Role and perspective
263
+ sections.push(`# Role: ${roleFraming.role}\n`);
264
+ sections.push(roleFraming.perspective);
265
+ sections.push("");
266
+ // Variant instruction
267
+ sections.push(VARIANT_INSTRUCTIONS[variant]);
268
+ sections.push("");
269
+ // Task header
270
+ sections.push(`# Task: ${card.title}`);
271
+ if (contextOpts.includeColumn && column) {
272
+ sections.push(`**Status:** ${column.name}`);
273
+ }
274
+ if (contextOpts.includePriority) {
275
+ sections.push(`**Priority:** ${card.priority}`);
276
+ }
277
+ if (contextOpts.includeDueDate && card.due_date) {
278
+ sections.push(`**Due:** ${card.due_date}`);
279
+ }
280
+ if (contextOpts.includeAssignee && card.assignee) {
281
+ sections.push(`**Assignee:** ${card.assignee.full_name || card.assignee.email}`);
282
+ }
283
+ // Labels
284
+ if (contextOpts.includeLabels && labels.length > 0) {
285
+ sections.push(formatLabels(labels));
286
+ }
287
+ // Description
288
+ if (contextOpts.includeDescription && card.description) {
289
+ sections.push(`\n## Description\n${card.description}`);
290
+ }
291
+ // Subtasks
292
+ if (contextOpts.includeSubtasks && subtasks.length > 0) {
293
+ sections.push(formatSubtasks(subtasks));
294
+ }
295
+ // Linked cards
296
+ if (contextOpts.includeLinks && links.length > 0) {
297
+ sections.push(formatLinkedCards(links));
298
+ }
299
+ // Focus areas
300
+ sections.push(`\n## Focus Areas`);
301
+ roleFraming.focus.forEach((f) => {
302
+ sections.push(`- ${f}`);
303
+ });
304
+ // Output suggestions
305
+ sections.push(`\n## Suggested Outputs`);
306
+ roleFraming.outputSuggestions.forEach((s) => {
307
+ sections.push(`- ${s}`);
308
+ });
309
+ // Relevant memories from knowledge graph
310
+ if (assembledContext) {
311
+ // Use pre-assembled context from context assembly engine
312
+ sections.push(`\n${assembledContext}`);
313
+ }
314
+ else if (memories && memories.length > 0) {
315
+ // Fallback: legacy memory format
316
+ sections.push(`\n## Relevant Memories`);
317
+ sections.push(`*${memories.length} memories recalled from knowledge graph:*`);
318
+ for (const memory of memories) {
319
+ const tags = memory.tags.length > 0 ? ` [${memory.tags.join(", ")}]` : "";
320
+ sections.push(`\n### ${memory.title} (${memory.type}, confidence: ${memory.confidence})${tags}`);
321
+ sections.push(memory.content);
322
+ }
323
+ }
324
+ // "One Thing" synthesis — highest-leverage next action
325
+ const oneThingLine = synthesizeOneThing(card, subtasks, links, assembledContext);
326
+ if (oneThingLine) {
327
+ sections.push(`\n## Recommended Next Step\n${oneThingLine}`);
328
+ }
329
+ // Progress tracking (execute variant only)
330
+ if (variant === "execute") {
331
+ sections.push(`\n## Progress Tracking
332
+ Update your progress by calling \`harmony_update_agent_progress\` with \`currentTask\` describing what you're doing now:
333
+ - After exploring the codebase and understanding requirements (~20%)
334
+ - When you start implementing changes (~50%)
335
+ - When you move to testing or verification (~80%)
336
+ - When done, before ending the session (100%)
337
+
338
+ Keep \`currentTask\` specific (e.g., "Refactoring auth middleware" not "Working on card").`);
339
+ }
340
+ // Custom constraints
341
+ if (customConstraints) {
342
+ sections.push(`\n## Additional Instructions\n${customConstraints}`);
343
+ }
344
+ // Card reference footer
345
+ sections.push(`\n---\n*Card #${card.short_id} | Generated for ${variant} mode*`);
346
+ const prompt = sections.join("\n");
347
+ const memoryCount = assembledContext
348
+ ? (assembledContext.match(/^### /gm) || []).length
349
+ : memories?.length || 0;
350
+ return {
351
+ prompt,
352
+ variant,
353
+ category,
354
+ role: roleFraming.role,
355
+ contextSummary: {
356
+ hasDescription: !!card.description,
357
+ labelCount: labels.length,
358
+ subtaskCount: subtasks.length,
359
+ completedSubtasks: subtasks.filter((s) => s.completed).length,
360
+ linkedCardCount: links.length,
361
+ memoryCount,
362
+ },
363
+ tokenEstimate: estimateTokens(prompt),
364
+ ...(assemblyId && { assemblyId }),
365
+ };
366
+ }
367
+ /**
368
+ * Extract session insights from assembled context string.
369
+ * Parses session summaries, blockers, and progress data.
370
+ */
371
+ function extractSessionInsights(assembledContext) {
372
+ const result = {
373
+ lastSessionStatus: null,
374
+ lastSessionTask: null,
375
+ lastSessionProgress: null,
376
+ blockers: [],
377
+ procedureNextStep: null,
378
+ };
379
+ // Find the most recent session summary with status
380
+ const sessionMatches = assembledContext.match(/### Session:.*?\n([\s\S]*?)(?=\n###|\n## |\n---|\n\*Assembly|$)/g);
381
+ if (sessionMatches && sessionMatches.length > 0) {
382
+ const latest = sessionMatches[0];
383
+ if (/Completed work on/i.test(latest)) {
384
+ result.lastSessionStatus = "completed";
385
+ }
386
+ else if (/Paused work on|status:\s*paused/i.test(latest)) {
387
+ result.lastSessionStatus = "paused";
388
+ }
389
+ const taskMatch = latest.match(/Final task:\s*(.+)/);
390
+ if (taskMatch)
391
+ result.lastSessionTask = taskMatch[1].trim();
392
+ const progressMatch = latest.match(/Progress:\s*(\d+)%/);
393
+ if (progressMatch)
394
+ result.lastSessionProgress = parseInt(progressMatch[1], 10);
395
+ }
396
+ // Extract blockers from context
397
+ const blockerMatches = assembledContext.match(/(?:blocker|blocked by|blocking):\s*(.+)/gi);
398
+ if (blockerMatches) {
399
+ result.blockers = blockerMatches.map((m) => m.replace(/(?:blocker|blocked by|blocking):\s*/i, "").trim());
400
+ }
401
+ // Extract next procedure step (first uncompleted step)
402
+ const stepMatches = assembledContext.match(/^\d+\.\s+(?!.*\*\*\[key step\]\*\*.*✓)(.+?)(?:\s*\*\*\[key step\]\*\*)?$/gm);
403
+ if (stepMatches && stepMatches.length > 0) {
404
+ result.procedureNextStep = stepMatches[0]
405
+ .replace(/^\d+\.\s+/, "")
406
+ .replace(/\s*\*\*\[key step\]\*\*.*$/, "")
407
+ .trim();
408
+ }
409
+ return result;
410
+ }
411
+ /**
412
+ * Synthesize the single highest-leverage next action from card state
413
+ * and assembled context (session history, blockers, procedures).
414
+ * Inspired by ArtemXTech's "One Thing" pattern in /recall.
415
+ */
416
+ function synthesizeOneThing(card, subtasks, links, assembledContext) {
417
+ // Priority 1: Card is already done
418
+ if (card.done)
419
+ return null;
420
+ // Priority 2: Blocked by another card (via links)
421
+ const blockers = links.filter((l) => l.display_type === "is_blocked_by" && l.direction === "incoming");
422
+ if (blockers.length > 0) {
423
+ const blocker = blockers[0];
424
+ return `Unblock first: resolve #${blocker.target_card.short_id} "${blocker.target_card.title}" which is blocking this card.`;
425
+ }
426
+ // Extract session insights from assembled context
427
+ const session = assembledContext
428
+ ? extractSessionInsights(assembledContext)
429
+ : null;
430
+ // Priority 3: Blockers detected in session context
431
+ if (session?.blockers && session.blockers.length > 0) {
432
+ return `Resolve blocker: ${session.blockers[0]}`;
433
+ }
434
+ // Priority 4: Previous session was paused — resume where it left off
435
+ if (session?.lastSessionStatus === "paused" && session.lastSessionTask) {
436
+ const progress = session.lastSessionProgress
437
+ ? ` (was ${session.lastSessionProgress}% complete)`
438
+ : "";
439
+ return `Resume previous session${progress}: "${session.lastSessionTask}".`;
440
+ }
441
+ // Priority 5: Has subtasks — find the first incomplete one
442
+ if (subtasks.length > 0) {
443
+ const completed = subtasks.filter((s) => s.completed).length;
444
+ if (completed === subtasks.length) {
445
+ return "All subtasks completed. Review the work and mark the card as done.";
446
+ }
447
+ const nextSubtask = subtasks.find((s) => !s.completed);
448
+ if (nextSubtask) {
449
+ return `Work on next subtask: "${nextSubtask.title}" (${completed}/${subtasks.length} done).`;
450
+ }
451
+ }
452
+ // Priority 6: Procedure has a next step
453
+ if (session?.procedureNextStep) {
454
+ return `Follow procedure: ${session.procedureNextStep}`;
455
+ }
456
+ // Priority 7: Previous session completed — build on it
457
+ if (session?.lastSessionStatus === "completed" && session.lastSessionTask) {
458
+ return `Previous session completed ("${session.lastSessionTask}"). Review results and continue with remaining work.`;
459
+ }
460
+ // Priority 8: High/urgent priority with due date
461
+ if (card.due_date &&
462
+ (card.priority === "urgent" || card.priority === "high")) {
463
+ return `High-priority task with deadline ${card.due_date}. Start implementation immediately.`;
464
+ }
465
+ // Priority 9: Has description — start working
466
+ if (card.description) {
467
+ return "Analyze the description, identify the approach, and begin implementation.";
468
+ }
469
+ // Fallback
470
+ return null;
471
+ }
472
+ /**
473
+ * Get all available categories
474
+ */
475
+ export function getAvailableCategories() {
476
+ return ["bug", "feature", "design", "review", "onboarding", "epic", "custom"];
477
+ }
478
+ /**
479
+ * Get all available variants
480
+ */
481
+ export function getAvailableVariants() {
482
+ return ["analysis", "draft", "execute"];
483
+ }
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Remote MCP Server for Harmony
4
+ *
5
+ * Hosted MCP endpoint that any AI agent can connect to via HTTP.
6
+ * Auth via API key passed as Bearer token, validated against the Harmony API.
7
+ *
8
+ * Usage:
9
+ * Claude.ai → POST https://mcp.gethmy.com/mcp (Bearer: hmy_xxx)
10
+ *
11
+ * Env vars:
12
+ * HARMONY_API_URL - Harmony API base URL (default: https://gethmy.com/api)
13
+ * PORT - Listen port (default: 3002)
14
+ */
15
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
16
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
17
+ import { serve } from "bun";
18
+ import { Hono } from "hono";
19
+ import { cors } from "hono/cors";
20
+ import { HarmonyApiClient } from "./api-client.js";
21
+ import { registerHandlers } from "./server.js";
22
+ // ---------------------------------------------------------------------------
23
+ // Config from env
24
+ // ---------------------------------------------------------------------------
25
+ const HARMONY_API_URL = process.env.HARMONY_API_URL || "https://gethmy.com/api";
26
+ const PORT = parseInt(process.env.PORT || "3002", 10);
27
+ async function validateApiKey(apiKey) {
28
+ try {
29
+ const response = await fetch(`${HARMONY_API_URL}/v1/workspaces`, {
30
+ headers: { "X-API-Key": apiKey },
31
+ });
32
+ if (!response.ok)
33
+ return null;
34
+ const data = (await response.json());
35
+ const firstWorkspace = data.workspaces?.[0];
36
+ return { workspaceId: firstWorkspace?.id ?? null };
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const sessions = new Map();
43
+ // Clean up stale sessions every 30 minutes
44
+ setInterval(() => {
45
+ const now = Date.now();
46
+ const maxAge = 60 * 60 * 1000; // 1 hour
47
+ for (const [id, session] of sessions) {
48
+ if (now - session.createdAt > maxAge) {
49
+ session.transport.close().catch(() => { });
50
+ sessions.delete(id);
51
+ }
52
+ }
53
+ }, 30 * 60 * 1000);
54
+ function createSession(apiKey, keyInfo) {
55
+ const transport = new WebStandardStreamableHTTPServerTransport({
56
+ sessionIdGenerator: () => crypto.randomUUID(),
57
+ enableJsonResponse: true,
58
+ });
59
+ const server = new Server({ name: "harmony-mcp-remote", version: "1.0.0" }, { capabilities: { tools: {}, resources: {} } });
60
+ const session = {
61
+ transport,
62
+ server,
63
+ apiKey,
64
+ activeWorkspaceId: keyInfo.workspaceId,
65
+ activeProjectId: null,
66
+ createdAt: Date.now(),
67
+ };
68
+ // Create per-session deps
69
+ const client = new HarmonyApiClient({ apiKey, apiUrl: HARMONY_API_URL });
70
+ const deps = {
71
+ getClient: () => client,
72
+ isConfigured: () => true,
73
+ getActiveProjectId: () => session.activeProjectId,
74
+ getActiveWorkspaceId: () => session.activeWorkspaceId,
75
+ setActiveProject: (id) => {
76
+ session.activeProjectId = id;
77
+ },
78
+ setActiveWorkspace: (id) => {
79
+ session.activeWorkspaceId = id;
80
+ },
81
+ getApiUrl: () => HARMONY_API_URL,
82
+ getMemoryDir: () => null, // No local filesystem in remote mode
83
+ getUserEmail: () => null,
84
+ saveConfig: () => { }, // No-op in remote mode
85
+ resetClient: () => { }, // No-op in remote mode
86
+ };
87
+ registerHandlers(server, deps);
88
+ // Clean up session when transport closes
89
+ transport.onclose = () => {
90
+ if (transport.sessionId) {
91
+ sessions.delete(transport.sessionId);
92
+ }
93
+ };
94
+ return session;
95
+ }
96
+ // ---------------------------------------------------------------------------
97
+ // Hono app
98
+ // ---------------------------------------------------------------------------
99
+ const app = new Hono();
100
+ app.use("/*", cors({
101
+ origin: "*",
102
+ allowMethods: ["GET", "POST", "DELETE", "OPTIONS"],
103
+ allowHeaders: [
104
+ "Content-Type",
105
+ "Authorization",
106
+ "Mcp-Session-Id",
107
+ "Mcp-Protocol-Version",
108
+ ],
109
+ exposeHeaders: ["Mcp-Session-Id"],
110
+ }));
111
+ // Health check
112
+ app.get("/health", (c) => c.json({
113
+ status: "ok",
114
+ service: "harmony-mcp-remote",
115
+ sessions: sessions.size,
116
+ }));
117
+ // MCP endpoint - handles POST (JSON-RPC), GET (SSE), DELETE (session close)
118
+ app.all("/mcp", async (c) => {
119
+ const method = c.req.method;
120
+ // Extract API key from Authorization header
121
+ const authHeader = c.req.header("Authorization");
122
+ if (!authHeader?.startsWith("Bearer ")) {
123
+ return c.json({ error: "Missing Authorization: Bearer <api-key>" }, 401);
124
+ }
125
+ const apiKey = authHeader.slice(7);
126
+ // Check for existing session
127
+ const sessionId = c.req.header("Mcp-Session-Id");
128
+ if (sessionId && sessions.has(sessionId)) {
129
+ // Existing session - forward request
130
+ const session = sessions.get(sessionId);
131
+ return session.transport.handleRequest(c.req.raw);
132
+ }
133
+ if (method === "POST") {
134
+ // Could be a new session (initialize) or an existing session we don't know about
135
+ // Validate API key
136
+ const keyInfo = await validateApiKey(apiKey);
137
+ if (!keyInfo) {
138
+ return c.json({ error: "Invalid API key" }, 401);
139
+ }
140
+ // Create new session
141
+ const session = createSession(apiKey, keyInfo);
142
+ // Connect server to transport
143
+ await session.server.connect(session.transport);
144
+ // Store session once transport has a session ID
145
+ const origOnSessionInitialized = session.transport._onsessioninitialized;
146
+ session.transport._onsessioninitialized = (sid) => {
147
+ sessions.set(sid, session);
148
+ origOnSessionInitialized?.(sid);
149
+ };
150
+ // Handle the initialize request
151
+ return session.transport.handleRequest(c.req.raw);
152
+ }
153
+ // GET or DELETE without a valid session
154
+ return c.json({ error: "Invalid or missing session" }, 404);
155
+ });
156
+ // ---------------------------------------------------------------------------
157
+ // Start server
158
+ // ---------------------------------------------------------------------------
159
+ console.log(`Starting Harmony Remote MCP server on port ${PORT}...`);
160
+ serve({
161
+ fetch: app.fetch,
162
+ port: PORT,
163
+ });
164
+ console.log(`Harmony Remote MCP server running at http://localhost:${PORT}`);
165
+ console.log(`MCP endpoint: http://localhost:${PORT}/mcp`);
166
+ console.log(`Health check: http://localhost:${PORT}/health`);