@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,359 @@
1
+ // src/runner.ts
2
+ import { CORE_TOOLSET, redactSecrets } from "@drumcode/core";
3
+ var DrumcodeRunner = class {
4
+ options;
5
+ toolCache = /* @__PURE__ */ new Map();
6
+ manifestCache = null;
7
+ constructor(options) {
8
+ this.options = options;
9
+ this.log("info", "Drumcode Runner initialized", {
10
+ registryUrl: options.registryUrl,
11
+ cacheEnabled: options.cacheEnabled
12
+ });
13
+ }
14
+ // ---------------------------------------------------------------------------
15
+ // Tool Discovery
16
+ // ---------------------------------------------------------------------------
17
+ /**
18
+ * Get the list of tools to expose to the client
19
+ * Uses Polyfill strategy for non-Anthropic clients
20
+ */
21
+ async getToolList(capabilities) {
22
+ if (capabilities.supportsAdvancedToolUse && capabilities.supportsDeferredLoading) {
23
+ this.log("debug", "Using Strategy A: Full manifest with deferred loading");
24
+ return this.getFullManifest();
25
+ }
26
+ this.log("debug", "Using Strategy B: Polyfill mode with core toolset");
27
+ return CORE_TOOLSET;
28
+ }
29
+ /**
30
+ * Fetch the full tool manifest from the Registry
31
+ */
32
+ async getFullManifest() {
33
+ if (this.manifestCache && this.options.cacheEnabled) {
34
+ return this.manifestCache;
35
+ }
36
+ try {
37
+ const response = await fetch(`${this.options.registryUrl}/v1/manifest`, {
38
+ headers: this.getAuthHeaders()
39
+ });
40
+ if (!response.ok) {
41
+ throw new Error(`Registry returned ${response.status}`);
42
+ }
43
+ const data = await response.json();
44
+ this.manifestCache = data.tools;
45
+ return this.manifestCache;
46
+ } catch (error) {
47
+ this.log("warn", "Failed to fetch manifest, using cached or fallback", { error });
48
+ return this.manifestCache || CORE_TOOLSET;
49
+ }
50
+ }
51
+ // ---------------------------------------------------------------------------
52
+ // Tool Execution
53
+ // ---------------------------------------------------------------------------
54
+ /**
55
+ * Execute a tool call
56
+ */
57
+ async executeTool(request) {
58
+ const startTime = Date.now();
59
+ try {
60
+ if (request.name === "drumcode_search_tools") {
61
+ return this.handleSearchTools(request.arguments);
62
+ }
63
+ if (request.name === "drumcode_get_tool_schema") {
64
+ return this.handleGetToolSchema(request.arguments);
65
+ }
66
+ return this.executeRegularTool(request);
67
+ } catch (error) {
68
+ const latency = Date.now() - startTime;
69
+ this.log("error", "Tool execution failed", {
70
+ tool: request.name,
71
+ error,
72
+ latencyMs: latency
73
+ });
74
+ return {
75
+ content: [{
76
+ type: "text",
77
+ text: `Error executing tool: ${error instanceof Error ? error.message : "Unknown error"}`
78
+ }],
79
+ isError: true
80
+ };
81
+ }
82
+ }
83
+ /**
84
+ * Handle drumcode_search_tools meta-tool
85
+ */
86
+ async handleSearchTools(args) {
87
+ this.log("debug", "Searching tools", { query: args.query });
88
+ try {
89
+ const response = await fetch(`${this.options.registryUrl}/v1/tools/search`, {
90
+ method: "POST",
91
+ headers: {
92
+ ...this.getAuthHeaders(),
93
+ "Content-Type": "application/json"
94
+ },
95
+ body: JSON.stringify({
96
+ query: args.query,
97
+ project_token: this.options.token,
98
+ limit: 5
99
+ })
100
+ });
101
+ if (!response.ok) {
102
+ throw new Error(`Search failed with status ${response.status}`);
103
+ }
104
+ const data = await response.json();
105
+ const resultText = data.matches.length > 0 ? data.matches.map(
106
+ (m, i) => `${i + 1}. **${m.name}** (relevance: ${(m.relevance * 100).toFixed(0)}%)
107
+ ${m.description}`
108
+ ).join("\n\n") : "No matching tools found. Try a different search query.";
109
+ return {
110
+ content: [{
111
+ type: "text",
112
+ text: `Found ${data.matches.length} matching tools:
113
+
114
+ ${resultText}
115
+
116
+ Use \`drumcode_get_tool_schema\` to get detailed arguments for any of these tools.`
117
+ }]
118
+ };
119
+ } catch (error) {
120
+ this.log("error", "Search failed", { error });
121
+ return {
122
+ content: [{
123
+ type: "text",
124
+ text: `Search failed: ${error instanceof Error ? error.message : "Unknown error"}`
125
+ }],
126
+ isError: true
127
+ };
128
+ }
129
+ }
130
+ /**
131
+ * Handle drumcode_get_tool_schema meta-tool
132
+ */
133
+ async handleGetToolSchema(args) {
134
+ this.log("debug", "Fetching tool schema", { toolName: args.tool_name });
135
+ if (this.toolCache.has(args.tool_name)) {
136
+ const cached = this.toolCache.get(args.tool_name);
137
+ return {
138
+ content: [{
139
+ type: "text",
140
+ text: this.formatToolSchema(cached)
141
+ }]
142
+ };
143
+ }
144
+ try {
145
+ const response = await fetch(
146
+ `${this.options.registryUrl}/v1/tools/${encodeURIComponent(args.tool_name)}`,
147
+ { headers: this.getAuthHeaders() }
148
+ );
149
+ if (!response.ok) {
150
+ if (response.status === 404) {
151
+ return {
152
+ content: [{
153
+ type: "text",
154
+ text: `Tool "${args.tool_name}" not found. Use drumcode_search_tools to find available tools.`
155
+ }],
156
+ isError: true
157
+ };
158
+ }
159
+ throw new Error(`Failed to fetch schema: ${response.status}`);
160
+ }
161
+ const schema = await response.json();
162
+ const tool = {
163
+ name: schema.name,
164
+ description: schema.description,
165
+ input_schema: schema.input_schema
166
+ };
167
+ this.toolCache.set(args.tool_name, tool);
168
+ return {
169
+ content: [{
170
+ type: "text",
171
+ text: this.formatToolSchema(tool)
172
+ }]
173
+ };
174
+ } catch (error) {
175
+ this.log("error", "Schema fetch failed", { error });
176
+ return {
177
+ content: [{
178
+ type: "text",
179
+ text: `Failed to fetch schema: ${error instanceof Error ? error.message : "Unknown error"}`
180
+ }],
181
+ isError: true
182
+ };
183
+ }
184
+ }
185
+ /**
186
+ * Execute a regular (non-meta) tool
187
+ */
188
+ async executeRegularTool(request) {
189
+ if (request.name === "drumcode_echo") {
190
+ return {
191
+ content: [{
192
+ type: "text",
193
+ text: JSON.stringify(request.arguments, null, 2)
194
+ }]
195
+ };
196
+ }
197
+ if (request.name === "drumcode_http_get") {
198
+ const url = request.arguments.url;
199
+ try {
200
+ const response = await fetch(url);
201
+ const text = await response.text();
202
+ return {
203
+ content: [{
204
+ type: "text",
205
+ text: `Status: ${response.status}
206
+
207
+ ${text.slice(0, 5e3)}${text.length > 5e3 ? "...(truncated)" : ""}`
208
+ }]
209
+ };
210
+ } catch (error) {
211
+ return {
212
+ content: [{
213
+ type: "text",
214
+ text: `HTTP request failed: ${error instanceof Error ? error.message : "Unknown error"}`
215
+ }],
216
+ isError: true
217
+ };
218
+ }
219
+ }
220
+ return {
221
+ content: [{
222
+ type: "text",
223
+ text: `Tool "${request.name}" is not yet implemented. This tool needs to be fetched and executed via the Registry.`
224
+ }],
225
+ isError: true
226
+ };
227
+ }
228
+ // ---------------------------------------------------------------------------
229
+ // Helpers
230
+ // ---------------------------------------------------------------------------
231
+ getAuthHeaders() {
232
+ const headers = {
233
+ "User-Agent": "drumcode-runner/0.1.0"
234
+ };
235
+ if (this.options.token) {
236
+ headers["Authorization"] = `Bearer ${this.options.token}`;
237
+ }
238
+ return headers;
239
+ }
240
+ formatToolSchema(tool) {
241
+ const props = tool.input_schema.properties;
242
+ const required = tool.input_schema.required || [];
243
+ const argsDescription = Object.entries(props).map(([name, prop]) => {
244
+ const req = required.includes(name) ? " (required)" : " (optional)";
245
+ return ` - ${name}${req}: ${prop.type}${prop.description ? ` - ${prop.description}` : ""}`;
246
+ }).join("\n");
247
+ return `## ${tool.name}
248
+
249
+ ${tool.description}
250
+
251
+ ### Arguments:
252
+ ${argsDescription || " No arguments required."}
253
+
254
+ ### Usage:
255
+ Call this tool with the arguments above to execute it.`;
256
+ }
257
+ log(level, message, data) {
258
+ const levels = ["debug", "info", "warn", "error"];
259
+ const currentLevel = levels.indexOf(this.options.logLevel);
260
+ const messageLevel = levels.indexOf(level);
261
+ if (messageLevel >= currentLevel) {
262
+ const safeData = data ? JSON.parse(redactSecrets(JSON.stringify(data))) : void 0;
263
+ const logFn = console[level] || console.log;
264
+ logFn(`[drumcode] ${message}`, safeData ? safeData : "");
265
+ }
266
+ }
267
+ };
268
+
269
+ // src/server.ts
270
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
271
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
272
+ import {
273
+ CallToolRequestSchema,
274
+ ListToolsRequestSchema
275
+ } from "@modelcontextprotocol/sdk/types.js";
276
+ async function createServer(options) {
277
+ const runner = new DrumcodeRunner(options);
278
+ const server = new Server(
279
+ {
280
+ name: "drumcode",
281
+ version: "0.1.0"
282
+ },
283
+ {
284
+ capabilities: {
285
+ tools: {}
286
+ }
287
+ }
288
+ );
289
+ server.setRequestHandler(ListToolsRequestSchema, async (request) => {
290
+ const capabilities = detectClientCapabilities(request);
291
+ const tools = await runner.getToolList(capabilities);
292
+ const demoTools = [
293
+ {
294
+ name: "drumcode_echo",
295
+ description: "Echo back the input arguments. Useful for testing.",
296
+ input_schema: {
297
+ type: "object",
298
+ properties: {
299
+ message: {
300
+ type: "string",
301
+ description: "The message to echo back"
302
+ }
303
+ },
304
+ required: ["message"]
305
+ }
306
+ },
307
+ {
308
+ name: "drumcode_http_get",
309
+ description: "Make an HTTP GET request to a URL and return the response.",
310
+ input_schema: {
311
+ type: "object",
312
+ properties: {
313
+ url: {
314
+ type: "string",
315
+ description: "The URL to fetch"
316
+ }
317
+ },
318
+ required: ["url"]
319
+ }
320
+ }
321
+ ];
322
+ const allTools = [...tools, ...demoTools].map((t) => ({
323
+ name: t.name,
324
+ description: t.description,
325
+ inputSchema: {
326
+ type: "object",
327
+ properties: t.input_schema.properties,
328
+ required: t.input_schema.required
329
+ }
330
+ }));
331
+ return { tools: allTools };
332
+ });
333
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
334
+ const { name, arguments: args } = request.params;
335
+ const result = await runner.executeTool({
336
+ name,
337
+ arguments: args ?? {}
338
+ });
339
+ return {
340
+ content: result.content,
341
+ isError: result.isError
342
+ };
343
+ });
344
+ const transport = new StdioServerTransport();
345
+ await server.connect(transport);
346
+ console.error("[drumcode] MCP Server started");
347
+ }
348
+ function detectClientCapabilities(_request) {
349
+ return {
350
+ type: "unknown",
351
+ supportsAdvancedToolUse: false,
352
+ supportsDeferredLoading: false
353
+ };
354
+ }
355
+
356
+ export {
357
+ DrumcodeRunner,
358
+ createServer
359
+ };