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