@drumcode/runner 0.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.
@@ -0,0 +1,1061 @@
1
+ // src/runner.ts
2
+ import { CORE_TOOLSET, redactSecrets } from "@drumcode/core";
3
+ var DrumcodeRunner = class {
4
+ options;
5
+ toolCache = /* @__PURE__ */ new Map();
6
+ skillCache = /* @__PURE__ */ new Map();
7
+ manifestCache = null;
8
+ authContext = {
9
+ isAuthenticated: false,
10
+ projectId: null,
11
+ tokenId: null,
12
+ tokenName: null,
13
+ profileId: null
14
+ };
15
+ authInitialized = false;
16
+ constructor(options) {
17
+ this.options = options;
18
+ this.log("info", "Drumcode Runner initialized", {
19
+ registryUrl: options.registryUrl,
20
+ cacheEnabled: options.cacheEnabled
21
+ });
22
+ }
23
+ // ---------------------------------------------------------------------------
24
+ // Authentication
25
+ // ---------------------------------------------------------------------------
26
+ /**
27
+ * Initialize authentication by validating the token with the registry
28
+ * This should be called before processing any requests
29
+ */
30
+ async initializeAuth() {
31
+ if (this.authInitialized) {
32
+ return this.authContext;
33
+ }
34
+ if (!this.options.token) {
35
+ this.log("info", "No token provided, running in demo mode");
36
+ this.authInitialized = true;
37
+ return this.authContext;
38
+ }
39
+ try {
40
+ this.log("debug", "Validating token with registry");
41
+ const response = await fetch(`${this.options.registryUrl}/v1/auth/token`, {
42
+ method: "POST",
43
+ headers: this.getAuthHeaders()
44
+ });
45
+ if (!response.ok) {
46
+ const errorData = await response.json().catch(() => ({}));
47
+ this.log("warn", "Token validation failed", {
48
+ status: response.status,
49
+ error: errorData.error?.message
50
+ });
51
+ this.authInitialized = true;
52
+ return this.authContext;
53
+ }
54
+ const data = await response.json();
55
+ if (data.valid && data.project && data.token) {
56
+ this.authContext = {
57
+ isAuthenticated: true,
58
+ projectId: data.project.id,
59
+ tokenId: data.token.id,
60
+ tokenName: data.token.name,
61
+ profileId: data.token.profileId
62
+ };
63
+ this.log("info", "Token validated successfully", {
64
+ projectId: this.authContext.projectId,
65
+ tokenName: this.authContext.tokenName,
66
+ hasProfile: !!this.authContext.profileId
67
+ });
68
+ }
69
+ } catch (error) {
70
+ this.log("error", "Token validation error", {
71
+ error: error instanceof Error ? error.message : "Unknown error"
72
+ });
73
+ }
74
+ this.authInitialized = true;
75
+ return this.authContext;
76
+ }
77
+ /**
78
+ * Get the current authentication context
79
+ */
80
+ getAuthContext() {
81
+ return this.authContext;
82
+ }
83
+ /**
84
+ * Check if the runner is authenticated
85
+ */
86
+ isAuthenticated() {
87
+ return this.authContext.isAuthenticated;
88
+ }
89
+ // ---------------------------------------------------------------------------
90
+ // Tool Discovery
91
+ // ---------------------------------------------------------------------------
92
+ /**
93
+ * Get the list of tools to expose to the client
94
+ * Uses Polyfill strategy for non-Anthropic clients
95
+ */
96
+ async getToolList(capabilities) {
97
+ if (capabilities.supportsAdvancedToolUse && capabilities.supportsDeferredLoading) {
98
+ this.log("debug", "Using Strategy A: Full manifest with deferred loading");
99
+ return this.getFullManifest();
100
+ }
101
+ this.log("debug", "Using Strategy B: Polyfill mode with core toolset");
102
+ return CORE_TOOLSET;
103
+ }
104
+ /**
105
+ * Fetch the full tool manifest from the Registry
106
+ */
107
+ async getFullManifest() {
108
+ if (this.manifestCache && this.options.cacheEnabled) {
109
+ return this.manifestCache;
110
+ }
111
+ try {
112
+ const response = await fetch(`${this.options.registryUrl}/v1/manifest`, {
113
+ headers: this.getAuthHeaders()
114
+ });
115
+ if (!response.ok) {
116
+ throw new Error(`Registry returned ${response.status}`);
117
+ }
118
+ const data = await response.json();
119
+ this.manifestCache = data.tools;
120
+ return this.manifestCache;
121
+ } catch (error) {
122
+ this.log("warn", "Failed to fetch manifest, using cached or fallback", { error });
123
+ return this.manifestCache || CORE_TOOLSET;
124
+ }
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // Tool Execution
128
+ // ---------------------------------------------------------------------------
129
+ /**
130
+ * Execute a tool call
131
+ */
132
+ async executeTool(request) {
133
+ const startTime = Date.now();
134
+ try {
135
+ if (request.name === "drumcode_search_tools") {
136
+ return this.handleSearchTools(request.arguments);
137
+ }
138
+ if (request.name === "drumcode_get_tool_schema") {
139
+ return this.handleGetToolSchema(request.arguments);
140
+ }
141
+ return this.executeRegularTool(request);
142
+ } catch (error) {
143
+ const latency = Date.now() - startTime;
144
+ this.log("error", "Tool execution failed", {
145
+ tool: request.name,
146
+ error,
147
+ latencyMs: latency
148
+ });
149
+ return {
150
+ content: [{
151
+ type: "text",
152
+ text: `Error executing tool: ${error instanceof Error ? error.message : "Unknown error"}`
153
+ }],
154
+ isError: true
155
+ };
156
+ }
157
+ }
158
+ /**
159
+ * Handle drumcode_search_tools meta-tool
160
+ */
161
+ async handleSearchTools(args) {
162
+ this.log("debug", "Searching tools", { query: args.query });
163
+ try {
164
+ const response = await fetch(`${this.options.registryUrl}/v1/tools/search`, {
165
+ method: "POST",
166
+ headers: {
167
+ ...this.getAuthHeaders(),
168
+ "Content-Type": "application/json"
169
+ },
170
+ body: JSON.stringify({
171
+ query: args.query,
172
+ project_token: this.options.token,
173
+ limit: 5
174
+ })
175
+ });
176
+ if (!response.ok) {
177
+ throw new Error(`Search failed with status ${response.status}`);
178
+ }
179
+ const data = await response.json();
180
+ const resultText = data.matches.length > 0 ? data.matches.map(
181
+ (m, i) => `${i + 1}. **${m.name}** (relevance: ${(m.relevance * 100).toFixed(0)}%)
182
+ ${m.description}`
183
+ ).join("\n\n") : "No matching tools found. Try a different search query.";
184
+ return {
185
+ content: [{
186
+ type: "text",
187
+ text: `Found ${data.matches.length} matching tools:
188
+
189
+ ${resultText}
190
+
191
+ Use \`drumcode_get_tool_schema\` to get detailed arguments for any of these tools.`
192
+ }]
193
+ };
194
+ } catch (error) {
195
+ this.log("error", "Search failed", { error });
196
+ return {
197
+ content: [{
198
+ type: "text",
199
+ text: `Search failed: ${error instanceof Error ? error.message : "Unknown error"}`
200
+ }],
201
+ isError: true
202
+ };
203
+ }
204
+ }
205
+ /**
206
+ * Handle drumcode_get_tool_schema meta-tool
207
+ */
208
+ async handleGetToolSchema(args) {
209
+ this.log("debug", "Fetching tool schema", { toolName: args.tool_name });
210
+ if (this.toolCache.has(args.tool_name)) {
211
+ const cached = this.toolCache.get(args.tool_name);
212
+ return {
213
+ content: [{
214
+ type: "text",
215
+ text: this.formatToolSchema(cached)
216
+ }]
217
+ };
218
+ }
219
+ try {
220
+ const response = await fetch(
221
+ `${this.options.registryUrl}/v1/tools/${encodeURIComponent(args.tool_name)}`,
222
+ { headers: this.getAuthHeaders() }
223
+ );
224
+ if (!response.ok) {
225
+ if (response.status === 404) {
226
+ return {
227
+ content: [{
228
+ type: "text",
229
+ text: `Tool "${args.tool_name}" not found. Use drumcode_search_tools to find available tools.`
230
+ }],
231
+ isError: true
232
+ };
233
+ }
234
+ throw new Error(`Failed to fetch schema: ${response.status}`);
235
+ }
236
+ const schema = await response.json();
237
+ const tool = {
238
+ name: schema.name,
239
+ description: schema.description,
240
+ input_schema: schema.input_schema
241
+ };
242
+ this.toolCache.set(args.tool_name, tool);
243
+ return {
244
+ content: [{
245
+ type: "text",
246
+ text: this.formatToolSchema(tool)
247
+ }]
248
+ };
249
+ } catch (error) {
250
+ this.log("error", "Schema fetch failed", { error });
251
+ return {
252
+ content: [{
253
+ type: "text",
254
+ text: `Failed to fetch schema: ${error instanceof Error ? error.message : "Unknown error"}`
255
+ }],
256
+ isError: true
257
+ };
258
+ }
259
+ }
260
+ async fetchRegistryToolSchema(name) {
261
+ try {
262
+ const response = await fetch(
263
+ `${this.options.registryUrl}/v1/tools/${encodeURIComponent(name)}`,
264
+ { headers: this.getAuthHeaders() }
265
+ );
266
+ if (!response.ok) {
267
+ if (response.status === 404) {
268
+ return null;
269
+ }
270
+ this.log("warn", "Registry tool fetch failed", { name, status: response.status });
271
+ return null;
272
+ }
273
+ return await response.json();
274
+ } catch (error) {
275
+ this.log("error", "Registry tool fetch error", { name, error });
276
+ return null;
277
+ }
278
+ }
279
+ /**
280
+ * Execute a regular (non-meta) tool
281
+ */
282
+ async executeRegularTool(request) {
283
+ if (request.name === "drumcode_echo") {
284
+ return {
285
+ content: [{
286
+ type: "text",
287
+ text: JSON.stringify(request.arguments, null, 2)
288
+ }]
289
+ };
290
+ }
291
+ if (request.name === "drumcode_http_get") {
292
+ const url = request.arguments.url;
293
+ try {
294
+ const response = await fetch(url);
295
+ const text = await response.text();
296
+ return {
297
+ content: [{
298
+ type: "text",
299
+ text: `Status: ${response.status}
300
+
301
+ ${text.slice(0, 5e3)}${text.length > 5e3 ? "...(truncated)" : ""}`
302
+ }]
303
+ };
304
+ } catch (error) {
305
+ return {
306
+ content: [{
307
+ type: "text",
308
+ text: `HTTP request failed: ${error instanceof Error ? error.message : "Unknown error"}`
309
+ }],
310
+ isError: true
311
+ };
312
+ }
313
+ }
314
+ if (request.name.startsWith("arxiv_")) {
315
+ return this.executeArxivTool(request);
316
+ }
317
+ const skill = await this.fetchSkill(request.name);
318
+ if (skill) {
319
+ return this.executeSkill(skill, request.arguments);
320
+ }
321
+ const registryResult = await this.executeRegistryTool(request);
322
+ if (registryResult) {
323
+ return registryResult;
324
+ }
325
+ return {
326
+ content: [{
327
+ type: "text",
328
+ text: `Tool "${request.name}" is not yet implemented. This tool needs to be fetched and executed via the Registry.`
329
+ }],
330
+ isError: true
331
+ };
332
+ }
333
+ async executeRegistryTool(request) {
334
+ const schema = await this.fetchRegistryToolSchema(request.name);
335
+ if (!schema) {
336
+ return null;
337
+ }
338
+ if (!schema.http_method || !schema.http_path) {
339
+ return {
340
+ content: [{
341
+ type: "text",
342
+ text: `Tool "${request.name}" is missing http_method/http_path in the registry.`
343
+ }],
344
+ isError: true
345
+ };
346
+ }
347
+ const integrationName = schema.integration?.name;
348
+ const baseUrl = this.getIntegrationBaseUrl(integrationName);
349
+ if (!baseUrl) {
350
+ return {
351
+ content: [{
352
+ type: "text",
353
+ text: `Missing base URL for integration "${integrationName || "unknown"}". Set DRUMCODE_INTEGRATION_BASE_URLS for this integration.`
354
+ }],
355
+ isError: true
356
+ };
357
+ }
358
+ const method = schema.http_method.toUpperCase();
359
+ let requestUrl;
360
+ let body;
361
+ try {
362
+ ({ url: requestUrl, body } = this.buildToolRequest(
363
+ baseUrl,
364
+ schema.http_path,
365
+ request.arguments,
366
+ method
367
+ ));
368
+ } catch (error) {
369
+ return {
370
+ content: [{
371
+ type: "text",
372
+ text: `Failed to build request for "${request.name}": ${error instanceof Error ? error.message : "Unknown error"}`
373
+ }],
374
+ isError: true
375
+ };
376
+ }
377
+ const headers = {
378
+ ...this.getIntegrationHeaders(integrationName)
379
+ };
380
+ if (body && !headers["Content-Type"]) {
381
+ headers["Content-Type"] = "application/json";
382
+ }
383
+ try {
384
+ const response = await fetch(requestUrl, {
385
+ method,
386
+ headers,
387
+ body: body ? JSON.stringify(body) : void 0
388
+ });
389
+ const text = await response.text();
390
+ const truncated = text.length > 5e3 ? "...(truncated)" : "";
391
+ return {
392
+ content: [{
393
+ type: "text",
394
+ text: `Status: ${response.status}
395
+
396
+ ${text.slice(0, 5e3)}${truncated}`
397
+ }],
398
+ isError: !response.ok
399
+ };
400
+ } catch (error) {
401
+ return {
402
+ content: [{
403
+ type: "text",
404
+ text: `HTTP request failed: ${error instanceof Error ? error.message : "Unknown error"}`
405
+ }],
406
+ isError: true
407
+ };
408
+ }
409
+ }
410
+ // ---------------------------------------------------------------------------
411
+ // Skill Execution
412
+ // ---------------------------------------------------------------------------
413
+ /**
414
+ * Fetch skill definition from registry
415
+ */
416
+ async fetchSkill(name) {
417
+ if (this.skillCache.has(name)) {
418
+ return this.skillCache.get(name);
419
+ }
420
+ try {
421
+ const response = await fetch(
422
+ `${this.options.registryUrl}/v1/skills/${encodeURIComponent(name)}`,
423
+ { headers: this.getAuthHeaders() }
424
+ );
425
+ if (!response.ok) {
426
+ if (response.status === 404) {
427
+ return null;
428
+ }
429
+ this.log("warn", "Skill fetch failed", { name, status: response.status });
430
+ return null;
431
+ }
432
+ const skill = await response.json();
433
+ this.skillCache.set(name, skill);
434
+ this.log("debug", "Fetched skill", { name, type: skill.skill_type });
435
+ return skill;
436
+ } catch (error) {
437
+ this.log("error", "Skill fetch error", { name, error });
438
+ return null;
439
+ }
440
+ }
441
+ /**
442
+ * Execute a skill (validator or workflow)
443
+ */
444
+ async executeSkill(skill, input) {
445
+ this.log("info", "Executing skill", { name: skill.name, type: skill.skill_type });
446
+ const steps = skill.logic_layer.steps;
447
+ const stepResults = {};
448
+ const context = { input, steps: stepResults };
449
+ try {
450
+ for (let i = 0; i < steps.length; i++) {
451
+ const step = steps[i];
452
+ if (step.action === "check_policy") {
453
+ const policyStep = step;
454
+ const passed = this.evaluateRule(policyStep.rule, context);
455
+ if (!passed) {
456
+ this.log("warn", "Policy check failed", {
457
+ skill: skill.name,
458
+ step: i,
459
+ rule: policyStep.rule
460
+ });
461
+ return {
462
+ content: [{
463
+ type: "text",
464
+ text: `Validation failed: ${policyStep.error_msg}`
465
+ }],
466
+ isError: true
467
+ };
468
+ }
469
+ this.log("debug", "Policy check passed", { step: i });
470
+ } else if (step.action === "execute_atomic") {
471
+ const execStep = step;
472
+ const toolArgs = {};
473
+ if (execStep.args_map) {
474
+ for (const [argName, mapping] of Object.entries(execStep.args_map)) {
475
+ toolArgs[argName] = this.evaluateMapping(mapping, context);
476
+ }
477
+ } else {
478
+ Object.assign(toolArgs, input);
479
+ }
480
+ this.log("debug", "Executing atomic tool", {
481
+ tool: execStep.tool,
482
+ args: Object.keys(toolArgs)
483
+ });
484
+ const result = await this.executeTool({
485
+ name: execStep.tool,
486
+ arguments: toolArgs
487
+ });
488
+ if (execStep.output_key) {
489
+ stepResults[execStep.output_key] = this.parseToolResult(result);
490
+ }
491
+ if (i === steps.length - 1 && !skill.logic_layer.output) {
492
+ return result;
493
+ }
494
+ }
495
+ }
496
+ if (skill.logic_layer.output) {
497
+ const output = {};
498
+ for (const [key, mapping] of Object.entries(skill.logic_layer.output)) {
499
+ output[key] = this.evaluateMapping(mapping, context);
500
+ }
501
+ return {
502
+ content: [{
503
+ type: "text",
504
+ text: JSON.stringify(output, null, 2)
505
+ }]
506
+ };
507
+ }
508
+ return {
509
+ content: [{
510
+ type: "text",
511
+ text: `Skill "${skill.name}" completed successfully.`
512
+ }]
513
+ };
514
+ } catch (error) {
515
+ this.log("error", "Skill execution failed", { skill: skill.name, error });
516
+ return {
517
+ content: [{
518
+ type: "text",
519
+ text: `Skill execution failed: ${error instanceof Error ? error.message : "Unknown error"}`
520
+ }],
521
+ isError: true
522
+ };
523
+ }
524
+ }
525
+ /**
526
+ * Evaluate a policy rule against context
527
+ * Simple expression evaluator for rules like "input.query && input.query.length >= 2"
528
+ */
529
+ evaluateRule(rule, context) {
530
+ try {
531
+ const { input, steps } = context;
532
+ const evalFn = new Function("input", "steps", `
533
+ try {
534
+ return Boolean(${rule});
535
+ } catch (e) {
536
+ return false;
537
+ }
538
+ `);
539
+ return evalFn(input, steps);
540
+ } catch (error) {
541
+ this.log("error", "Rule evaluation failed", { rule, error });
542
+ return false;
543
+ }
544
+ }
545
+ /**
546
+ * Evaluate an argument mapping expression
547
+ * Supports expressions like "input.query", "input.max_results || 5", "steps.search_results.papers[0].id"
548
+ */
549
+ evaluateMapping(mapping, context) {
550
+ try {
551
+ const { input, steps } = context;
552
+ const evalFn = new Function("input", "steps", `
553
+ try {
554
+ return ${mapping};
555
+ } catch (e) {
556
+ return undefined;
557
+ }
558
+ `);
559
+ return evalFn(input, steps);
560
+ } catch (error) {
561
+ this.log("error", "Mapping evaluation failed", { mapping, error });
562
+ return void 0;
563
+ }
564
+ }
565
+ /**
566
+ * Parse tool result content to extract structured data
567
+ */
568
+ parseToolResult(result) {
569
+ if (result.isError) {
570
+ return { error: true, message: result.content[0]?.text };
571
+ }
572
+ const text = result.content[0]?.text || "";
573
+ try {
574
+ return JSON.parse(text);
575
+ } catch {
576
+ if (text.includes("Found") && text.includes("papers")) {
577
+ const papers = [];
578
+ const paperMatches = text.matchAll(/ID: ([^\n]+)[\s\S]*?\*\*([^*]+)\*\*/g);
579
+ for (const match of paperMatches) {
580
+ papers.push({ id: match[1].trim(), title: match[2].trim() });
581
+ }
582
+ const altMatches = text.matchAll(/\*\*([^*]+)\*\*[^(]*\(([^)]+)\)/g);
583
+ for (const match of altMatches) {
584
+ if (!papers.find((p) => p.id === match[2].trim())) {
585
+ papers.push({ id: match[2].trim(), title: match[1].trim() });
586
+ }
587
+ }
588
+ return { papers, raw: text };
589
+ }
590
+ return { raw: text };
591
+ }
592
+ }
593
+ /**
594
+ * Execute arXiv tools via the arXiv API
595
+ */
596
+ async executeArxivTool(request) {
597
+ const baseUrl = "http://export.arxiv.org/api/query";
598
+ try {
599
+ switch (request.name) {
600
+ case "arxiv_search_papers": {
601
+ const { query, max_results = 10, categories } = request.arguments;
602
+ let searchQuery = query;
603
+ if (categories && categories.length > 0) {
604
+ const catFilter = categories.map((c) => `cat:${c}`).join(" OR ");
605
+ searchQuery = `(${query}) AND (${catFilter})`;
606
+ }
607
+ const params = new URLSearchParams({
608
+ search_query: `all:${searchQuery}`,
609
+ start: "0",
610
+ max_results: String(Math.min(max_results, 20)),
611
+ sortBy: "submittedDate",
612
+ sortOrder: "descending"
613
+ });
614
+ const response = await fetch(`${baseUrl}?${params}`);
615
+ const xml = await response.text();
616
+ const papers = this.parseArxivResponse(xml);
617
+ return {
618
+ content: [{
619
+ type: "text",
620
+ text: `Found ${papers.length} papers:
621
+
622
+ ${papers.map(
623
+ (p, i) => `${i + 1}. **${p.title}**
624
+ ID: ${p.id}
625
+ Authors: ${p.authors}
626
+ Published: ${p.published}
627
+ ${p.summary.slice(0, 200)}...`
628
+ ).join("\n\n")}`
629
+ }]
630
+ };
631
+ }
632
+ case "arxiv_get_paper":
633
+ case "arxiv_get_abstract": {
634
+ const { paper_id } = request.arguments;
635
+ const params = new URLSearchParams({ id_list: paper_id });
636
+ const response = await fetch(`${baseUrl}?${params}`);
637
+ const xml = await response.text();
638
+ const papers = this.parseArxivResponse(xml);
639
+ if (papers.length === 0) {
640
+ return {
641
+ content: [{ type: "text", text: `Paper ${paper_id} not found.` }],
642
+ isError: true
643
+ };
644
+ }
645
+ const p = papers[0];
646
+ return {
647
+ content: [{
648
+ type: "text",
649
+ text: `**${p.title}**
650
+
651
+ ID: ${p.id}
652
+ Authors: ${p.authors}
653
+ Published: ${p.published}
654
+ Categories: ${p.categories}
655
+ PDF: ${p.pdf_url}
656
+
657
+ **Abstract:**
658
+ ${p.summary}`
659
+ }]
660
+ };
661
+ }
662
+ case "arxiv_search_by_author": {
663
+ const { author, max_results = 10 } = request.arguments;
664
+ const params = new URLSearchParams({
665
+ search_query: `au:${author}`,
666
+ start: "0",
667
+ max_results: String(Math.min(max_results, 20)),
668
+ sortBy: "submittedDate",
669
+ sortOrder: "descending"
670
+ });
671
+ const response = await fetch(`${baseUrl}?${params}`);
672
+ const xml = await response.text();
673
+ const papers = this.parseArxivResponse(xml);
674
+ return {
675
+ content: [{
676
+ type: "text",
677
+ text: `Found ${papers.length} papers by "${author}":
678
+
679
+ ${papers.map(
680
+ (p, i) => `${i + 1}. **${p.title}** (${p.id})
681
+ ${p.published}`
682
+ ).join("\n\n")}`
683
+ }]
684
+ };
685
+ }
686
+ case "arxiv_search_by_category": {
687
+ const { category, max_results = 10 } = request.arguments;
688
+ const params = new URLSearchParams({
689
+ search_query: `cat:${category}`,
690
+ start: "0",
691
+ max_results: String(Math.min(max_results, 20)),
692
+ sortBy: "submittedDate",
693
+ sortOrder: "descending"
694
+ });
695
+ const response = await fetch(`${baseUrl}?${params}`);
696
+ const xml = await response.text();
697
+ const papers = this.parseArxivResponse(xml);
698
+ return {
699
+ content: [{
700
+ type: "text",
701
+ text: `Found ${papers.length} recent papers in ${category}:
702
+
703
+ ${papers.map(
704
+ (p, i) => `${i + 1}. **${p.title}** (${p.id})
705
+ Authors: ${p.authors}
706
+ ${p.published}`
707
+ ).join("\n\n")}`
708
+ }]
709
+ };
710
+ }
711
+ default:
712
+ return {
713
+ content: [{
714
+ type: "text",
715
+ text: `arXiv tool "${request.name}" is not yet implemented.`
716
+ }],
717
+ isError: true
718
+ };
719
+ }
720
+ } catch (error) {
721
+ this.log("error", "arXiv API call failed", { error });
722
+ return {
723
+ content: [{
724
+ type: "text",
725
+ text: `arXiv API error: ${error instanceof Error ? error.message : "Unknown error"}`
726
+ }],
727
+ isError: true
728
+ };
729
+ }
730
+ }
731
+ /**
732
+ * Parse arXiv Atom XML response
733
+ */
734
+ parseArxivResponse(xml) {
735
+ const papers = [];
736
+ const entryRegex = /<entry>([\s\S]*?)<\/entry>/g;
737
+ let match;
738
+ while ((match = entryRegex.exec(xml)) !== null) {
739
+ const entry = match[1];
740
+ const getId = (s) => {
741
+ const m = s.match(/<id>(.*?)<\/id>/);
742
+ return m ? m[1].replace("http://arxiv.org/abs/", "") : "";
743
+ };
744
+ const getTitle = (s) => {
745
+ const m = s.match(/<title>([\s\S]*?)<\/title>/);
746
+ return m ? m[1].replace(/\s+/g, " ").trim() : "";
747
+ };
748
+ const getSummary = (s) => {
749
+ const m = s.match(/<summary>([\s\S]*?)<\/summary>/);
750
+ return m ? m[1].replace(/\s+/g, " ").trim() : "";
751
+ };
752
+ const getAuthors = (s) => {
753
+ const authors = [];
754
+ const authorRegex = /<author>\s*<name>(.*?)<\/name>/g;
755
+ let authorMatch;
756
+ while ((authorMatch = authorRegex.exec(s)) !== null) {
757
+ authors.push(authorMatch[1]);
758
+ }
759
+ return authors.join(", ");
760
+ };
761
+ const getPublished = (s) => {
762
+ const m = s.match(/<published>(.*?)<\/published>/);
763
+ return m ? m[1].split("T")[0] : "";
764
+ };
765
+ const getCategories = (s) => {
766
+ const cats = [];
767
+ const catRegex = /<category[^>]*term="([^"]+)"/g;
768
+ let catMatch;
769
+ while ((catMatch = catRegex.exec(s)) !== null) {
770
+ cats.push(catMatch[1]);
771
+ }
772
+ return cats.join(", ");
773
+ };
774
+ const getPdfUrl = (s) => {
775
+ const m = s.match(/<link[^>]*title="pdf"[^>]*href="([^"]+)"/);
776
+ return m ? m[1] : "";
777
+ };
778
+ papers.push({
779
+ id: getId(entry),
780
+ title: getTitle(entry),
781
+ summary: getSummary(entry),
782
+ authors: getAuthors(entry),
783
+ published: getPublished(entry),
784
+ categories: getCategories(entry),
785
+ pdf_url: getPdfUrl(entry)
786
+ });
787
+ }
788
+ return papers;
789
+ }
790
+ // ---------------------------------------------------------------------------
791
+ // Helpers
792
+ // ---------------------------------------------------------------------------
793
+ getIntegrationBaseUrl(integrationName) {
794
+ if (!integrationName) {
795
+ return this.options.integrationBaseUrls?.default || null;
796
+ }
797
+ const direct = this.options.integrationBaseUrls?.[integrationName] || this.options.integrationBaseUrls?.[integrationName.toLowerCase()];
798
+ return direct || this.options.integrationBaseUrls?.default || null;
799
+ }
800
+ getIntegrationHeaders(integrationName) {
801
+ if (!integrationName) {
802
+ return this.options.integrationHeaders?.default || {};
803
+ }
804
+ return this.options.integrationHeaders?.[integrationName] || this.options.integrationHeaders?.[integrationName.toLowerCase()] || this.options.integrationHeaders?.default || {};
805
+ }
806
+ buildToolRequest(baseUrl, path, args, method) {
807
+ const normalizedBase = baseUrl.replace(/\/+$/, "");
808
+ let resolvedPath = path;
809
+ const remainingArgs = { ...args };
810
+ const pathParams = [...path.matchAll(/{([^}]+)}/g)].map((match) => match[1]);
811
+ for (const param of pathParams) {
812
+ const value = remainingArgs[param];
813
+ if (value === void 0 || value === null) {
814
+ throw new Error(`Missing required path param "${param}"`);
815
+ }
816
+ resolvedPath = resolvedPath.replace(`{${param}}`, encodeURIComponent(String(value)));
817
+ delete remainingArgs[param];
818
+ }
819
+ const normalizedPath = resolvedPath.startsWith("/") ? resolvedPath : `/${resolvedPath}`;
820
+ let url = `${normalizedBase}${normalizedPath}`;
821
+ if (method === "GET" || method === "DELETE") {
822
+ const params = new URLSearchParams();
823
+ for (const [key, value] of Object.entries(remainingArgs)) {
824
+ if (value === void 0 || value === null) continue;
825
+ if (Array.isArray(value)) {
826
+ for (const item of value) {
827
+ params.append(key, String(item));
828
+ }
829
+ continue;
830
+ }
831
+ if (typeof value === "object") {
832
+ params.append(key, JSON.stringify(value));
833
+ continue;
834
+ }
835
+ params.append(key, String(value));
836
+ }
837
+ const query = params.toString();
838
+ if (query) {
839
+ url = `${url}?${query}`;
840
+ }
841
+ return { url, body: null };
842
+ }
843
+ return { url, body: remainingArgs };
844
+ }
845
+ getAuthHeaders() {
846
+ const headers = {
847
+ "User-Agent": "drumcode-runner/0.1.0"
848
+ };
849
+ if (this.options.token) {
850
+ headers["Authorization"] = `Bearer ${this.options.token}`;
851
+ }
852
+ return headers;
853
+ }
854
+ formatToolSchema(tool) {
855
+ const props = tool.input_schema.properties;
856
+ const required = tool.input_schema.required || [];
857
+ const argsDescription = Object.entries(props).map(([name, prop]) => {
858
+ const req = required.includes(name) ? " (required)" : " (optional)";
859
+ return ` - ${name}${req}: ${prop.type}${prop.description ? ` - ${prop.description}` : ""}`;
860
+ }).join("\n");
861
+ return `## ${tool.name}
862
+
863
+ ${tool.description}
864
+
865
+ ### Arguments:
866
+ ${argsDescription || " No arguments required."}
867
+
868
+ ### Usage:
869
+ Call this tool with the arguments above to execute it.`;
870
+ }
871
+ log(level, message, data) {
872
+ const levels = ["debug", "info", "warn", "error"];
873
+ const currentLevel = levels.indexOf(this.options.logLevel);
874
+ const messageLevel = levels.indexOf(level);
875
+ if (messageLevel >= currentLevel) {
876
+ const safeData = data ? JSON.parse(redactSecrets(JSON.stringify(data))) : void 0;
877
+ console.error(`[drumcode] ${message}`, safeData ? safeData : "");
878
+ }
879
+ }
880
+ };
881
+
882
+ // src/server.ts
883
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
884
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
885
+ import {
886
+ CallToolRequestSchema,
887
+ ListToolsRequestSchema
888
+ } from "@modelcontextprotocol/sdk/types.js";
889
+ async function createServer(options) {
890
+ const runner = new DrumcodeRunner(options);
891
+ const authContext = await runner.initializeAuth();
892
+ if (authContext.isAuthenticated) {
893
+ console.error(`[drumcode] Authenticated as: ${authContext.tokenName || "unnamed token"}`);
894
+ console.error(`[drumcode] Project ID: ${authContext.projectId}`);
895
+ if (authContext.profileId) {
896
+ console.error(`[drumcode] Permission profile: ${authContext.profileId}`);
897
+ }
898
+ } else if (options.token) {
899
+ console.error("[drumcode] Warning: Token provided but authentication failed");
900
+ }
901
+ const server = new Server(
902
+ {
903
+ name: "drumcode",
904
+ version: "0.1.0"
905
+ },
906
+ {
907
+ capabilities: {
908
+ tools: {}
909
+ }
910
+ }
911
+ );
912
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
913
+ const capabilities = {
914
+ type: options.clientMode === "full" ? "anthropic" : "unknown",
915
+ supportsAdvancedToolUse: options.clientMode === "full",
916
+ supportsDeferredLoading: options.clientMode === "full"
917
+ };
918
+ const tools = await runner.getToolList(capabilities);
919
+ const includeAuxTools = options.clientMode === "full";
920
+ const demoTools = includeAuxTools ? [
921
+ {
922
+ name: "drumcode_echo",
923
+ description: "Echo back the input arguments. Useful for testing.",
924
+ input_schema: {
925
+ type: "object",
926
+ properties: {
927
+ message: {
928
+ type: "string",
929
+ description: "The message to echo back"
930
+ }
931
+ },
932
+ required: ["message"]
933
+ }
934
+ },
935
+ {
936
+ name: "drumcode_http_get",
937
+ description: "Make an HTTP GET request to a URL and return the response.",
938
+ input_schema: {
939
+ type: "object",
940
+ properties: {
941
+ url: {
942
+ type: "string",
943
+ description: "The URL to fetch"
944
+ }
945
+ },
946
+ required: ["url"]
947
+ }
948
+ }
949
+ ] : [];
950
+ const arxivTools = includeAuxTools ? [
951
+ {
952
+ name: "arxiv_search_papers",
953
+ description: "Search for academic papers on arXiv. Returns papers matching the query with optional filters.",
954
+ input_schema: {
955
+ type: "object",
956
+ properties: {
957
+ query: {
958
+ type: "string",
959
+ description: 'Search query keywords (e.g., "machine learning", "quantum computing")'
960
+ },
961
+ max_results: {
962
+ type: "number",
963
+ description: "Maximum number of results to return (1-20)"
964
+ },
965
+ categories: {
966
+ type: "string",
967
+ description: 'Comma-separated arXiv categories to filter by (e.g., "cs.AI,cs.LG")'
968
+ }
969
+ },
970
+ required: ["query"]
971
+ }
972
+ },
973
+ {
974
+ name: "arxiv_get_paper",
975
+ description: "Get detailed metadata and abstract for a specific paper by its arXiv ID.",
976
+ input_schema: {
977
+ type: "object",
978
+ properties: {
979
+ paper_id: {
980
+ type: "string",
981
+ description: 'The arXiv paper ID (e.g., "2301.07041" or "1706.03762")'
982
+ }
983
+ },
984
+ required: ["paper_id"]
985
+ }
986
+ },
987
+ {
988
+ name: "arxiv_search_by_author",
989
+ description: "Search for papers by a specific author on arXiv.",
990
+ input_schema: {
991
+ type: "object",
992
+ properties: {
993
+ author: {
994
+ type: "string",
995
+ description: "Author name to search for"
996
+ },
997
+ max_results: {
998
+ type: "number",
999
+ description: "Maximum number of results (1-20)"
1000
+ }
1001
+ },
1002
+ required: ["author"]
1003
+ }
1004
+ },
1005
+ {
1006
+ name: "arxiv_search_by_category",
1007
+ description: "Search for recent papers in a specific arXiv category.",
1008
+ input_schema: {
1009
+ type: "object",
1010
+ properties: {
1011
+ category: {
1012
+ type: "string",
1013
+ description: 'arXiv category (e.g., "cs.AI", "math.CO", "physics.hep-th")'
1014
+ },
1015
+ max_results: {
1016
+ type: "number",
1017
+ description: "Maximum number of results (1-20)"
1018
+ }
1019
+ },
1020
+ required: ["category"]
1021
+ }
1022
+ }
1023
+ ] : [];
1024
+ const toolMap = /* @__PURE__ */ new Map();
1025
+ for (const t of [...demoTools, ...arxivTools]) {
1026
+ toolMap.set(t.name, t);
1027
+ }
1028
+ for (const t of tools) {
1029
+ toolMap.set(t.name, t);
1030
+ }
1031
+ const allTools = Array.from(toolMap.values()).map((t) => ({
1032
+ name: t.name,
1033
+ description: t.description,
1034
+ inputSchema: {
1035
+ type: "object",
1036
+ properties: t.input_schema.properties,
1037
+ required: t.input_schema.required
1038
+ }
1039
+ }));
1040
+ return { tools: allTools };
1041
+ });
1042
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1043
+ const { name, arguments: args } = request.params;
1044
+ const result = await runner.executeTool({
1045
+ name,
1046
+ arguments: args ?? {}
1047
+ });
1048
+ return {
1049
+ content: result.content,
1050
+ isError: result.isError
1051
+ };
1052
+ });
1053
+ const transport = new StdioServerTransport();
1054
+ await server.connect(transport);
1055
+ console.error("[drumcode] MCP Server started");
1056
+ }
1057
+
1058
+ export {
1059
+ DrumcodeRunner,
1060
+ createServer
1061
+ };