@mcpc-tech/plugin-markdown-loader 0.0.8 → 0.0.9

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/index.mjs CHANGED
@@ -2,2003 +2,6 @@
2
2
  import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
4
 
5
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/compose.js
6
- import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
-
8
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
9
- var schemaSymbol = Symbol.for("mcpc.schema");
10
- var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
11
- var validatorSymbol = Symbol.for("mcpc.validator");
12
- function jsonSchema(schema, options = {}) {
13
- if (isWrappedSchema(schema)) {
14
- return schema;
15
- }
16
- return {
17
- [schemaSymbol]: true,
18
- [validatorSymbol]: true,
19
- _type: void 0,
20
- jsonSchema: schema,
21
- validate: options.validate
22
- };
23
- }
24
- function isWrappedSchema(value) {
25
- return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
26
- }
27
- function extractJsonSchema(schema) {
28
- if (isWrappedSchema(schema)) {
29
- return schema.jsonSchema;
30
- }
31
- return schema;
32
- }
33
-
34
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/compose.js
35
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
36
-
37
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/json.js
38
- import { jsonrepair } from "jsonrepair";
39
-
40
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/ai.js
41
- var p = (template, options = {}) => {
42
- const { missingVariableHandling = "warn" } = options;
43
- const names = /* @__PURE__ */ new Set();
44
- const regex = /\{((\w|\.)+)\}/g;
45
- let match;
46
- while ((match = regex.exec(template)) !== null) {
47
- names.add(match[1]);
48
- }
49
- const required = Array.from(names);
50
- return (input) => {
51
- let result = template;
52
- for (const name of required) {
53
- const key = name;
54
- const value = input[key];
55
- const re = new RegExp(`\\{${String(name)}\\}`, "g");
56
- if (value !== void 0 && value !== null) {
57
- result = result.replace(re, String(value));
58
- } else {
59
- switch (missingVariableHandling) {
60
- case "error":
61
- throw new Error(`Missing variable "${String(name)}" in input for template.`);
62
- case "empty":
63
- result = result.replace(re, "");
64
- break;
65
- case "warn":
66
- case "ignore":
67
- default:
68
- break;
69
- }
70
- }
71
- }
72
- return result;
73
- };
74
- };
75
-
76
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
77
- import { load } from "cheerio";
78
-
79
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
80
- import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
81
-
82
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__http/server_sent_event_stream.js
83
- var NEWLINE_REGEXP = /\r\n|\r|\n/;
84
- var encoder = new TextEncoder();
85
- function assertHasNoNewline(value, varName, errPrefix) {
86
- if (value.match(NEWLINE_REGEXP) !== null) {
87
- throw new SyntaxError(`${errPrefix}: ${varName} cannot contain a newline`);
88
- }
89
- }
90
- function stringify(message) {
91
- const lines = [];
92
- if (message.comment) {
93
- assertHasNoNewline(message.comment, "`message.comment`", "Cannot serialize message");
94
- lines.push(`:${message.comment}`);
95
- }
96
- if (message.event) {
97
- assertHasNoNewline(message.event, "`message.event`", "Cannot serialize message");
98
- lines.push(`event:${message.event}`);
99
- }
100
- if (message.data) {
101
- message.data.split(NEWLINE_REGEXP).forEach((line) => lines.push(`data:${line}`));
102
- }
103
- if (message.id) {
104
- assertHasNoNewline(message.id.toString(), "`message.id`", "Cannot serialize message");
105
- lines.push(`id:${message.id}`);
106
- }
107
- if (message.retry) lines.push(`retry:${message.retry}`);
108
- return encoder.encode(lines.join("\n") + "\n\n");
109
- }
110
- var ServerSentEventStream = class extends TransformStream {
111
- constructor() {
112
- super({
113
- transform: (message, controller) => {
114
- controller.enqueue(stringify(message));
115
- }
116
- });
117
- }
118
- };
119
-
120
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
121
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
122
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
123
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
124
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
125
- import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
126
-
127
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
128
- import process from "node:process";
129
- var GEMINI_PREFERRED_FORMAT = process.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
130
-
131
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
132
- import { jsonrepair as jsonrepair2 } from "jsonrepair";
133
-
134
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
135
- var createModelCompatibleJSONSchema = (schema) => {
136
- const validatorOnlyKeys = [
137
- "errorMessage"
138
- ];
139
- const geminiRestrictedKeys = GEMINI_PREFERRED_FORMAT ? [
140
- "additionalProperties"
141
- ] : [];
142
- const keysToRemove = /* @__PURE__ */ new Set([
143
- ...validatorOnlyKeys,
144
- ...geminiRestrictedKeys
145
- ]);
146
- let cleanSchema = schema;
147
- if (GEMINI_PREFERRED_FORMAT) {
148
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest } = schema;
149
- cleanSchema = rest;
150
- }
151
- const cleanRecursively = (obj) => {
152
- if (Array.isArray(obj)) {
153
- return obj.map(cleanRecursively);
154
- }
155
- if (obj && typeof obj === "object") {
156
- const result = {};
157
- for (const [key, value] of Object.entries(obj)) {
158
- if (!keysToRemove.has(key)) {
159
- result[key] = cleanRecursively(value);
160
- }
161
- }
162
- return result;
163
- }
164
- return obj;
165
- };
166
- return cleanRecursively(cleanSchema);
167
- };
168
- var INTERNAL_SCHEMA_KEYS = /* @__PURE__ */ new Set([
169
- "$schema",
170
- "_originalName",
171
- "_type",
172
- "annotations"
173
- ]);
174
- var cleanToolSchema = (schema) => {
175
- const cleanRecursively = (obj) => {
176
- if (Array.isArray(obj)) {
177
- return obj.map(cleanRecursively);
178
- }
179
- if (obj && typeof obj === "object") {
180
- const record = obj;
181
- if ("jsonSchema" in record && typeof record.jsonSchema === "object" && record.jsonSchema !== null) {
182
- return cleanRecursively(record.jsonSchema);
183
- }
184
- const result = {};
185
- for (const [key, value] of Object.entries(record)) {
186
- if (!INTERNAL_SCHEMA_KEYS.has(key)) {
187
- result[key] = cleanRecursively(value);
188
- }
189
- }
190
- return result;
191
- }
192
- return obj;
193
- };
194
- return cleanRecursively(schema);
195
- };
196
-
197
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
198
- import process2 from "node:process";
199
- var mcpClientPool = /* @__PURE__ */ new Map();
200
- var cleanupAllPooledClients = async () => {
201
- const entries = Array.from(mcpClientPool.entries());
202
- mcpClientPool.clear();
203
- await Promise.all(entries.map(async ([, { client }]) => {
204
- try {
205
- await client.close();
206
- } catch (err) {
207
- console.error("Error closing MCP client:", err);
208
- }
209
- }));
210
- };
211
- process2.once?.("exit", () => {
212
- cleanupAllPooledClients();
213
- });
214
- process2.once?.("SIGINT", () => {
215
- cleanupAllPooledClients().finally(() => process2.exit(0));
216
- });
217
-
218
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
219
- var createConfigPlugin = () => ({
220
- name: "built-in-config",
221
- version: "1.0.0",
222
- enforce: "pre",
223
- transformTool: (tool2, context2) => {
224
- const server = context2.server;
225
- const config = server.findToolConfig?.(context2.toolName);
226
- if (config?.description) {
227
- tool2.description = config.description;
228
- }
229
- return tool2;
230
- }
231
- });
232
- var config_plugin_default = createConfigPlugin();
233
-
234
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
235
- var createToolNameMappingPlugin = () => ({
236
- name: "built-in-tool-name-mapping",
237
- version: "1.0.0",
238
- enforce: "pre",
239
- transformTool: (tool2, context2) => {
240
- const server = context2.server;
241
- const toolName = context2.toolName;
242
- const originalName = tool2._originalName || toolName;
243
- const dotNotation = originalName.replace(/_/g, ".");
244
- const underscoreNotation = originalName.replace(/\./g, "_");
245
- if (dotNotation !== originalName && server.toolNameMapping) {
246
- server.toolNameMapping.set(dotNotation, toolName);
247
- }
248
- if (underscoreNotation !== originalName && server.toolNameMapping) {
249
- server.toolNameMapping.set(underscoreNotation, toolName);
250
- }
251
- if (originalName !== toolName && server.toolNameMapping) {
252
- server.toolNameMapping.set(originalName, toolName);
253
- }
254
- return tool2;
255
- }
256
- });
257
- var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
258
-
259
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
260
- var LOG_LEVELS = {
261
- debug: 0,
262
- info: 1,
263
- notice: 2,
264
- warning: 3,
265
- error: 4,
266
- critical: 5,
267
- alert: 6,
268
- emergency: 7
269
- };
270
- var MCPLogger = class _MCPLogger {
271
- server;
272
- loggerName;
273
- minLevel = "debug";
274
- constructor(loggerName = "mcpc", server) {
275
- this.loggerName = loggerName;
276
- this.server = server;
277
- }
278
- setServer(server) {
279
- this.server = server;
280
- }
281
- setLevel(level) {
282
- this.minLevel = level;
283
- }
284
- async log(level, data) {
285
- if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
286
- return;
287
- }
288
- this.logToConsole(level, data);
289
- if (this.server) {
290
- try {
291
- await this.server.sendLoggingMessage({
292
- level,
293
- logger: this.loggerName,
294
- data
295
- });
296
- } catch {
297
- }
298
- }
299
- }
300
- logToConsole(level, data) {
301
- const message = typeof data === "string" ? data : JSON.stringify(data);
302
- const prefix = `[${this.loggerName}:${level}]`;
303
- console.error(prefix, message);
304
- }
305
- debug(data) {
306
- return this.log("debug", data);
307
- }
308
- info(data) {
309
- return this.log("info", data);
310
- }
311
- notice(data) {
312
- return this.log("notice", data);
313
- }
314
- warning(data) {
315
- return this.log("warning", data);
316
- }
317
- error(data) {
318
- return this.log("error", data);
319
- }
320
- critical(data) {
321
- return this.log("critical", data);
322
- }
323
- alert(data) {
324
- return this.log("alert", data);
325
- }
326
- emergency(data) {
327
- return this.log("emergency", data);
328
- }
329
- child(name) {
330
- const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
331
- child.setLevel(this.minLevel);
332
- return child;
333
- }
334
- };
335
- var logger = new MCPLogger("mcpc");
336
- function createLogger(name, server) {
337
- return new MCPLogger(name, server);
338
- }
339
-
340
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
341
- var createLoggingPlugin = (options = {}) => {
342
- const { enabled = true, verbose = false, compact = true } = options;
343
- return {
344
- name: "built-in-logging",
345
- version: "1.0.0",
346
- composeEnd: async (context2) => {
347
- if (!enabled) return;
348
- const logger2 = createLogger("mcpc.plugin.logging", context2.server);
349
- if (compact) {
350
- const pluginCount = context2.pluginNames.length;
351
- const { stats } = context2;
352
- await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
353
- } else if (verbose) {
354
- await logger2.info(`[${context2.toolName}] Composition complete`);
355
- await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
356
- const { stats } = context2;
357
- const server = context2.server;
358
- const publicTools = Array.from(new Set(server.getPublicToolNames().map(String)));
359
- const internalTools = Array.from(new Set(server.getInternalToolNames().map(String)));
360
- const hiddenTools = Array.from(new Set(server.getHiddenToolNames().map(String)));
361
- const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
362
- if (publicTools.length > 0) {
363
- await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
364
- }
365
- if (internalTools.length > 0) {
366
- const parts = [];
367
- if (normalInternal.length > 0) {
368
- parts.push(normalInternal.join(", "));
369
- }
370
- if (hiddenTools.length > 0) {
371
- parts.push(`(${hiddenTools.join(", ")})`);
372
- }
373
- await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
374
- }
375
- await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
376
- }
377
- }
378
- };
379
- };
380
- var logging_plugin_default = createLoggingPlugin({
381
- verbose: true,
382
- compact: false
383
- });
384
-
385
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
386
- var SystemPrompts = {
387
- /**
388
- * Base system prompt for autonomous MCP execution
389
- *
390
- * Uses simplified Unix-style interface:
391
- * - `tool` + `args` for clean, consistent structure
392
- * - `man` command for fetching tool schemas (like Unix manual)
393
- * - No `hasDefinitions` - trusts model's context memory
394
- */
395
- AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes tasks by calling its tools, following the <manual/>, obeying the <rules/>, and using the <format/>.
396
-
397
- <manual>
398
- {description}
399
- </manual>
400
-
401
- <parameters>
402
- \`tool\` - Which tool to execute: "man" to get schemas, or a tool name to execute
403
- \`args\` - For "man": { tools: ["tool1", "tool2"] }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.
404
- </parameters>
405
-
406
- <rules>
407
- 1. **First call**: Use \`man\` to get tool schemas you need
408
- 2. **Execute tools**: Use tool name in \`tool\` and parameters in \`args\`
409
- </rules>
410
-
411
- <format>
412
- Get tool schemas: \`{ "tool": "man", "args": { "tools": ["tool1", "tool2"] } }\`
413
- Execute a tool: \`{ "tool": "tool_name", "args": { /* parameters */ } }\`
414
- </format>`,
415
- /**
416
- * Compact system prompt for autonomous MCP execution (when manual is provided)
417
- *
418
- * Uses simplified description with progressive disclosure:
419
- * - Short description shown by default
420
- * - Use `man` command with args `{ manual: true }` to get full manual
421
- */
422
- AUTONOMOUS_EXECUTION_COMPACT: `Agentic tool \`{toolName}\` that executes tasks by calling its tools, following the <rules/> and using the <format/>.
423
-
424
- {description}
425
-
426
- <rules>
427
- 1. **First call**: Use \`man\` to get tool schemas and full manual
428
- 2. **Execute tools**: Use tool name in \`tool\` and parameters in \`args\`
429
- </rules>
430
-
431
- <format>
432
- Get manual + schemas: \`{ "tool": "man", "args": { "tools": ["tool1"], "manual": true } }\`
433
- Execute a tool: \`{ "tool": "tool_name", "args": { /* parameters */ } }\`
434
- </format>`,
435
- /**
436
- * Tool description for sampling tools (shown in MCP tools list)
437
- * Explains how to use prompt and context parameters
438
- */
439
- SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
440
-
441
- You must follow the <manual/>, obey the <rules/>, and use the <format/>.
442
-
443
- <manual>
444
- {description}
445
- </manual>
446
-
447
- <format>
448
- \`prompt\` - The task to be completed (e.g., "organize my desktop files")
449
- \`context\` - Execution context object (e.g., { cwd: "/path/to/dir" })
450
- </format>
451
-
452
- <rules>
453
- 1. Always provide both \`prompt\` and \`context\` parameters
454
- 2. \`prompt\` must be a clear, actionable description
455
- 3. \`context\` must include relevant environment info (e.g., working directory)
456
- </rules>`,
457
- /**
458
- * System prompt for AI sampling loop (ai_sampling/ai_acp modes)
459
- * Used inside the execution loop when AI calls native tools.
460
- * Note: Tool schemas are passed via AI SDK native tool calling, not in prompt.
461
- */
462
- AI_LOOP_SYSTEM: `Agent \`{toolName}\` that completes tasks by calling tools.
463
-
464
- <manual>
465
- {description}
466
- </manual>
467
-
468
- <rules>
469
- {rules}
470
- </rules>{context}`
471
- };
472
- var ResponseTemplates = {
473
- /**
474
- * Error response templates
475
- */
476
- ERROR_RESPONSE: `Validation failed: {errorMessage}
477
-
478
- Adjust parameters and retry.`,
479
- /**
480
- * Security validation messages
481
- */
482
- SECURITY_VALIDATION: {
483
- PASSED: `Security check passed: {operation} on {path}`,
484
- FAILED: `Security check failed: {operation} on {path}`
485
- },
486
- /**
487
- * Audit log messages
488
- */
489
- AUDIT_LOG: `[{timestamp}] {level}: {action} on {resource}{userInfo}`
490
- };
491
- var CompiledPrompts = {
492
- autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
493
- autonomousExecutionCompact: p(SystemPrompts.AUTONOMOUS_EXECUTION_COMPACT),
494
- samplingToolDescription: p(SystemPrompts.SAMPLING_TOOL_DESCRIPTION),
495
- aiLoopSystem: p(SystemPrompts.AI_LOOP_SYSTEM),
496
- errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
497
- securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
498
- securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
499
- auditLog: p(ResponseTemplates.AUDIT_LOG)
500
- };
501
-
502
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
503
- function createArgsDefFactory(_name, _allToolNames, _depGroups, _predefinedSteps, _ensureStepActions) {
504
- return {
505
- forSampling: function() {
506
- return {
507
- type: "object",
508
- description: "Provide prompt for autonomous tool execution",
509
- properties: {
510
- prompt: {
511
- type: "string",
512
- description: "The task to be completed autonomously by the agentic system using available tools"
513
- },
514
- context: {
515
- type: "object",
516
- description: "Execution context, e.g., { cwd: '/path/to/dir' }. Any relevant fields allowed.",
517
- additionalProperties: true
518
- }
519
- },
520
- required: [
521
- "prompt",
522
- "context"
523
- ],
524
- errorMessage: {
525
- required: {
526
- prompt: "Missing required field 'prompt'. Please provide a clear task description.",
527
- context: "Missing required field 'context'. Please provide relevant context (e.g., { cwd: '...' })."
528
- }
529
- }
530
- };
531
- },
532
- /**
533
- * Agentic schema - simplified Unix-style interface
534
- *
535
- * Only two fields:
536
- * - `tool`: which tool to execute (enum includes "man" + all tool names)
537
- * - `args`: object with parameters. For "man": { tools: ["a", "b"] }. For others: tool parameters.
538
- */
539
- forAgentic: function(allToolNames) {
540
- const toolEnum = [
541
- "man",
542
- ...allToolNames
543
- ];
544
- return {
545
- type: "object",
546
- properties: {
547
- tool: {
548
- type: "string",
549
- enum: toolEnum,
550
- description: 'Which tool to execute. Use "man" to get tool schemas, or a tool name to execute.',
551
- errorMessage: {
552
- enum: `Invalid tool. Available: ${toolEnum.join(", ")}`
553
- }
554
- },
555
- args: {
556
- type: "object",
557
- description: `For "man": { tools: ["tool1", "tool2"], manual?: true }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.`
558
- }
559
- },
560
- required: [
561
- "tool"
562
- ],
563
- additionalProperties: false
564
- };
565
- },
566
- /**
567
- * Schema for "man" command args validation
568
- * Expected format: { tools: ["tool1", "tool2"], manual?: true }
569
- *
570
- * - Always require `tools`
571
- * - Allow empty tools only when `manual: true`
572
- */
573
- forMan: function(allToolNames) {
574
- return {
575
- type: "object",
576
- properties: {
577
- tools: {
578
- type: "array",
579
- items: {
580
- type: "string",
581
- enum: allToolNames,
582
- errorMessage: {
583
- enum: `Invalid tool name. Available: ${allToolNames.join(", ")}`
584
- }
585
- }
586
- },
587
- manual: {
588
- type: "boolean",
589
- description: "Set to true to get the full manual for this agent (progressive disclosure)."
590
- }
591
- },
592
- required: [
593
- "tools"
594
- ],
595
- additionalProperties: false,
596
- anyOf: [
597
- // manual-only (tools can be empty)
598
- {
599
- properties: {
600
- manual: {
601
- enum: [
602
- true
603
- ]
604
- },
605
- tools: {
606
- minItems: 0
607
- }
608
- },
609
- required: [
610
- "tools",
611
- "manual"
612
- ]
613
- },
614
- // tool schemas (require at least one tool)
615
- {
616
- properties: {
617
- tools: {
618
- minItems: 1,
619
- errorMessage: {
620
- minItems: "At least one tool name is required"
621
- }
622
- }
623
- },
624
- required: [
625
- "tools"
626
- ]
627
- }
628
- ],
629
- errorMessage: {
630
- required: {
631
- tools: 'Missing "tools" field. Expected: { tools: ["tool1", "tool2"] }'
632
- }
633
- }
634
- };
635
- }
636
- };
637
- }
638
-
639
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/schema-validator.js
640
- import { Ajv } from "ajv";
641
- import addFormats from "ajv-formats";
642
- import ajvErrors from "ajv-errors";
643
- import { AggregateAjvError } from "@segment/ajv-human-errors";
644
- var ajv = new Ajv({
645
- allErrors: true,
646
- verbose: true,
647
- strict: false
648
- });
649
- addFormats.default(ajv);
650
- ajvErrors.default(ajv);
651
- function validateSchema(data, schema) {
652
- const validate = ajv.compile(schema);
653
- if (!validate(data)) {
654
- const errors = validate.errors;
655
- const customErrors = errors.filter((err) => err.keyword === "errorMessage");
656
- if (customErrors.length > 0) {
657
- const messages = [
658
- ...new Set(customErrors.map((err) => err.message))
659
- ];
660
- return {
661
- valid: false,
662
- error: messages.join("; ")
663
- };
664
- }
665
- const aggregateError = new AggregateAjvError(errors);
666
- return {
667
- valid: false,
668
- error: aggregateError.message
669
- };
670
- }
671
- return {
672
- valid: true
673
- };
674
- }
675
-
676
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/tracing.js
677
- import { context, SpanStatusCode, trace } from "@opentelemetry/api";
678
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
679
- import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
680
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
681
- import { Resource } from "@opentelemetry/resources";
682
- import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
683
- var tracerProvider = null;
684
- var tracer = null;
685
- var isInitialized = false;
686
- function initializeTracing(config = {}) {
687
- if (isInitialized) {
688
- return;
689
- }
690
- const { enabled = true, serviceName = "mcpc-sampling", serviceVersion = "0.2.0", exportTo = "console", otlpEndpoint = "http://localhost:4318/v1/traces", otlpHeaders = {} } = config;
691
- if (!enabled) {
692
- isInitialized = true;
693
- return;
694
- }
695
- const resource = Resource.default().merge(new Resource({
696
- [ATTR_SERVICE_NAME]: serviceName,
697
- [ATTR_SERVICE_VERSION]: serviceVersion
698
- }));
699
- tracerProvider = new NodeTracerProvider({
700
- resource
701
- });
702
- if (exportTo === "console") {
703
- tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
704
- } else if (exportTo === "otlp") {
705
- const otlpExporter = new OTLPTraceExporter({
706
- url: otlpEndpoint,
707
- headers: otlpHeaders
708
- });
709
- tracerProvider.addSpanProcessor(new BatchSpanProcessor(otlpExporter));
710
- }
711
- tracerProvider.register();
712
- tracer = trace.getTracer(serviceName, serviceVersion);
713
- isInitialized = true;
714
- }
715
- function getTracer() {
716
- if (!isInitialized) {
717
- initializeTracing();
718
- }
719
- return tracer;
720
- }
721
- function startSpan(name, attributes, parent) {
722
- const tracer2 = getTracer();
723
- const ctx = parent ? trace.setSpan(context.active(), parent) : void 0;
724
- return tracer2.startSpan(name, {
725
- attributes
726
- }, ctx);
727
- }
728
- function endSpan(span, error) {
729
- if (error) {
730
- span.setStatus({
731
- code: SpanStatusCode.ERROR,
732
- message: error.message
733
- });
734
- span.recordException(error);
735
- } else {
736
- span.setStatus({
737
- code: SpanStatusCode.OK
738
- });
739
- }
740
- span.end();
741
- }
742
-
743
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
744
- import process3 from "node:process";
745
- var AgenticExecutor = class {
746
- name;
747
- allToolNames;
748
- toolNameToDetailList;
749
- server;
750
- manual;
751
- logger;
752
- tracingEnabled;
753
- toolSchemaMap;
754
- constructor(name, allToolNames, toolNameToDetailList, server, manual) {
755
- this.name = name;
756
- this.allToolNames = allToolNames;
757
- this.toolNameToDetailList = toolNameToDetailList;
758
- this.server = server;
759
- this.manual = manual;
760
- this.tracingEnabled = false;
761
- this.logger = createLogger(`mcpc.agentic.${name}`, server);
762
- this.toolSchemaMap = new Map(toolNameToDetailList);
763
- try {
764
- this.tracingEnabled = process3.env.MCPC_TRACING_ENABLED === "true";
765
- if (this.tracingEnabled) {
766
- initializeTracing({
767
- enabled: true,
768
- serviceName: `mcpc-agentic-${name}`,
769
- exportTo: process3.env.MCPC_TRACING_EXPORT ?? "otlp",
770
- otlpEndpoint: process3.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
771
- });
772
- }
773
- } catch {
774
- this.tracingEnabled = false;
775
- }
776
- }
777
- async execute(args, schema, parentSpan) {
778
- const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
779
- agent: this.name,
780
- tool: String(args.tool ?? "unknown"),
781
- args: JSON.stringify(args)
782
- }, parentSpan ?? void 0) : null;
783
- try {
784
- const validationResult = this.validate(args, schema);
785
- if (!validationResult.valid) {
786
- if (executeSpan) {
787
- executeSpan.setAttributes({
788
- validationError: true,
789
- errorMessage: validationResult.error || "Validation failed"
790
- });
791
- endSpan(executeSpan);
792
- }
793
- this.logger.warning({
794
- message: "Validation failed",
795
- tool: args.tool,
796
- error: validationResult.error
797
- });
798
- return {
799
- content: [
800
- {
801
- type: "text",
802
- text: CompiledPrompts.errorResponse({
803
- errorMessage: validationResult.error || "Validation failed"
804
- })
805
- }
806
- ],
807
- isError: true
808
- };
809
- }
810
- const tool2 = args.tool;
811
- if (tool2 === "man") {
812
- const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, {});
813
- const manSchema = createArgsDef.forMan(this.allToolNames);
814
- const manValidation = validateSchema(args.args ?? {}, manSchema);
815
- if (!manValidation.valid) {
816
- return {
817
- content: [
818
- {
819
- type: "text",
820
- text: `Invalid args for "man": ${manValidation.error}`
821
- }
822
- ],
823
- isError: true
824
- };
825
- }
826
- const argsObj = args.args;
827
- const tools = argsObj.tools ?? [];
828
- const wantManual = argsObj.manual === true;
829
- const wantTools = tools.length > 0;
830
- if (wantTools && wantManual) {
831
- const toolSchemas = this.handleManCommand(tools, null);
832
- const manualResult = this.handleManualRequest(null);
833
- if (executeSpan) {
834
- executeSpan.setAttributes({
835
- toolType: "man",
836
- requestType: "tools+manual"
837
- });
838
- endSpan(executeSpan);
839
- }
840
- return {
841
- content: [
842
- ...toolSchemas.content,
843
- {
844
- type: "text",
845
- text: "\n---\n"
846
- },
847
- ...manualResult.content
848
- ]
849
- };
850
- }
851
- if (wantManual) {
852
- return this.handleManualRequest(executeSpan);
853
- }
854
- return this.handleManCommand(tools, executeSpan);
855
- }
856
- const toolArgs = args.args || {};
857
- return await this.executeTool(tool2, toolArgs, executeSpan);
858
- } catch (error) {
859
- if (executeSpan) {
860
- endSpan(executeSpan, error);
861
- }
862
- this.logger.error({
863
- message: "Unexpected error in execute",
864
- error: String(error)
865
- });
866
- return {
867
- content: [
868
- {
869
- type: "text",
870
- text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
871
- }
872
- ],
873
- isError: true
874
- };
875
- }
876
- }
877
- /**
878
- * Handle `man { manual: true }` - return full manual for progressive disclosure
879
- */
880
- handleManualRequest(executeSpan) {
881
- if (executeSpan) {
882
- executeSpan.setAttributes({
883
- toolType: "man",
884
- requestType: "manual"
885
- });
886
- }
887
- if (!this.manual) {
888
- if (executeSpan) {
889
- endSpan(executeSpan);
890
- }
891
- return {
892
- content: [
893
- {
894
- type: "text",
895
- text: "No manual available for this agent."
896
- }
897
- ]
898
- };
899
- }
900
- if (executeSpan) {
901
- executeSpan.setAttributes({
902
- success: true
903
- });
904
- endSpan(executeSpan);
905
- }
906
- return {
907
- content: [
908
- {
909
- type: "text",
910
- text: this.manual
911
- }
912
- ]
913
- };
914
- }
915
- /**
916
- * Handle `man` command - return schemas for requested tools
917
- * @param requestedTools - Array of tool names (already validated via JSON Schema)
918
- */
919
- handleManCommand(requestedTools, executeSpan) {
920
- if (executeSpan) {
921
- executeSpan.setAttributes({
922
- toolType: "man",
923
- requestedTools: requestedTools.join(",")
924
- });
925
- }
926
- const schemas = requestedTools.map((toolName) => {
927
- const toolDetail = this.toolSchemaMap.get(toolName);
928
- if (toolDetail) {
929
- const cleanedSchema = cleanToolSchema(toolDetail);
930
- return `<tool_definition name="${toolName}">
931
- ${JSON.stringify(cleanedSchema, null, 2)}
932
- </tool_definition>`;
933
- }
934
- return null;
935
- }).filter(Boolean);
936
- if (executeSpan) {
937
- executeSpan.setAttributes({
938
- schemasReturned: schemas.length,
939
- success: true
940
- });
941
- endSpan(executeSpan);
942
- }
943
- return {
944
- content: [
945
- {
946
- type: "text",
947
- text: schemas.length > 0 ? schemas.join("\n\n") : "No schemas found for requested tools."
948
- }
949
- ]
950
- };
951
- }
952
- /**
953
- * Execute a tool with runtime validation
954
- */
955
- async executeTool(tool2, toolArgs, executeSpan) {
956
- const isExternalTool = this.toolNameToDetailList.some(([name]) => name === tool2);
957
- const isInternalTool = this.allToolNames.includes(tool2);
958
- if (!isExternalTool && !isInternalTool) {
959
- if (executeSpan) {
960
- executeSpan.setAttributes({
961
- toolType: "not_found",
962
- tool: tool2
963
- });
964
- endSpan(executeSpan);
965
- }
966
- return {
967
- content: [
968
- {
969
- type: "text",
970
- text: `Tool "${tool2}" not found. Available tools: ${this.allToolNames.join(", ")}`
971
- }
972
- ],
973
- isError: true
974
- };
975
- }
976
- if (isExternalTool) {
977
- const externalTool = this.toolNameToDetailList.find(([name]) => name === tool2);
978
- const [, toolDetail] = externalTool;
979
- if (toolDetail.inputSchema) {
980
- const rawSchema = extractJsonSchema(toolDetail.inputSchema);
981
- const validation = validateSchema(toolArgs, rawSchema);
982
- if (!validation.valid) {
983
- if (executeSpan) {
984
- executeSpan.setAttributes({
985
- validationError: true,
986
- errorMessage: validation.error
987
- });
988
- endSpan(executeSpan);
989
- }
990
- return {
991
- content: [
992
- {
993
- type: "text",
994
- text: `Parameter validation failed for "${tool2}": ${validation.error}`
995
- }
996
- ],
997
- isError: true
998
- };
999
- }
1000
- }
1001
- }
1002
- const toolType = isExternalTool ? "external" : "internal";
1003
- if (executeSpan) {
1004
- executeSpan.setAttributes({
1005
- toolType,
1006
- selectedTool: tool2
1007
- });
1008
- }
1009
- this.logger.debug({
1010
- message: `Executing ${toolType} tool`,
1011
- tool: tool2
1012
- });
1013
- try {
1014
- const result = await this.server.callTool(tool2, toolArgs, {
1015
- agentName: this.name
1016
- });
1017
- const callToolResult = result ?? {
1018
- content: []
1019
- };
1020
- if (executeSpan) {
1021
- executeSpan.setAttributes({
1022
- success: true,
1023
- isError: !!callToolResult.isError,
1024
- resultContentLength: callToolResult.content?.length || 0
1025
- });
1026
- endSpan(executeSpan);
1027
- }
1028
- return callToolResult;
1029
- } catch (error) {
1030
- if (executeSpan) {
1031
- endSpan(executeSpan, error);
1032
- }
1033
- this.logger.error({
1034
- message: `Error executing ${toolType} tool`,
1035
- tool: tool2,
1036
- error: String(error)
1037
- });
1038
- return {
1039
- content: [
1040
- {
1041
- type: "text",
1042
- text: `Error executing tool "${tool2}": ${error instanceof Error ? error.message : String(error)}`
1043
- }
1044
- ],
1045
- isError: true
1046
- };
1047
- }
1048
- }
1049
- validate(args, schema) {
1050
- return validateSchema(args, schema);
1051
- }
1052
- };
1053
-
1054
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
1055
- function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, manual }) {
1056
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1057
- const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server, manual);
1058
- description = manual ? CompiledPrompts.autonomousExecutionCompact({
1059
- toolName: name,
1060
- description
1061
- }) : CompiledPrompts.autonomousExecution({
1062
- toolName: name,
1063
- description
1064
- });
1065
- const agenticArgsDef = createArgsDef.forAgentic(allToolNames);
1066
- const schema = agenticArgsDef;
1067
- server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
1068
- return await agenticExecutor.execute(args, schema);
1069
- });
1070
- }
1071
-
1072
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
1073
- var createAgenticModePlugin = () => ({
1074
- name: "mode-agentic",
1075
- version: "2.0.0",
1076
- // Only apply to agentic mode
1077
- apply: "agentic",
1078
- // Register the agent tool
1079
- registerAgentTool: (context2) => {
1080
- registerAgenticTool(context2.server, {
1081
- description: context2.description,
1082
- name: context2.name,
1083
- allToolNames: context2.allToolNames,
1084
- depGroups: context2.depGroups,
1085
- toolNameToDetailList: context2.toolNameToDetailList,
1086
- manual: context2.manual
1087
- });
1088
- }
1089
- });
1090
- var mode_agentic_plugin_default = createAgenticModePlugin();
1091
-
1092
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/utils.js
1093
- function convertAISDKToMCPMessages(prompt) {
1094
- const messages = [];
1095
- for (const msg of prompt) {
1096
- if (msg.role === "system") continue;
1097
- const role = msg.role === "assistant" ? "assistant" : "user";
1098
- const textParts = msg.content.filter((c) => c.type === "text");
1099
- const toolCalls = msg.content.filter((c) => c.type === "tool-call");
1100
- const toolResults = msg.content.filter((c) => c.type === "tool-result");
1101
- const parts = [];
1102
- if (textParts.length > 0) {
1103
- parts.push(textParts.map((c) => c.text).join("\n"));
1104
- }
1105
- if (toolCalls.length > 0) {
1106
- const calls = toolCalls.map((c) => {
1107
- const call = c;
1108
- const toolArgs = call.args ?? call.input ?? {};
1109
- return `<use_tool tool="${call.toolName}">
1110
- ${JSON.stringify(toolArgs)}
1111
- </use_tool>`;
1112
- });
1113
- parts.push(calls.join("\n"));
1114
- }
1115
- if (toolResults.length > 0) {
1116
- const results = toolResults.map((c) => {
1117
- const result = c;
1118
- const resultValue = result.result ?? result.output ?? "undefined";
1119
- const output = JSON.stringify(resultValue);
1120
- return `Tool "${result.toolName}" result:
1121
- ${output}`;
1122
- });
1123
- parts.push(results.join("\n\n"));
1124
- }
1125
- const text = parts.join("\n\n");
1126
- if (text) {
1127
- messages.push({
1128
- role,
1129
- content: {
1130
- type: "text",
1131
- text
1132
- }
1133
- });
1134
- }
1135
- }
1136
- return messages;
1137
- }
1138
- function convertMCPStopReasonToAISDK(stopReason) {
1139
- if (stopReason === "endTurn" || stopReason === "stopSequence") {
1140
- return "stop";
1141
- }
1142
- if (stopReason === "maxTokens") return "length";
1143
- return stopReason ?? "unknown";
1144
- }
1145
-
1146
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/language-model.js
1147
- var DEFAULT_MAX_TOKENS = 128e3;
1148
- var MCPSamplingLanguageModel = class {
1149
- specificationVersion = "v2";
1150
- provider;
1151
- modelId;
1152
- supportedUrls = {};
1153
- server;
1154
- modelPreferences;
1155
- maxTokens;
1156
- constructor(config) {
1157
- this.server = config.server;
1158
- this.modelId = "";
1159
- this.provider = "mcp-client";
1160
- this.modelPreferences = config.modelPreferences;
1161
- this.maxTokens = config.maxTokens ?? DEFAULT_MAX_TOKENS;
1162
- }
1163
- /**
1164
- * Generate a response using MCP's createMessage capability
1165
- */
1166
- async doGenerate(options) {
1167
- const useNativeTools = this.supportsSamplingTools();
1168
- this.server.sendLoggingMessage({
1169
- level: "info",
1170
- data: `Client supports native tools: ${useNativeTools}`
1171
- });
1172
- const messages = this.convertMessages(options.prompt, useNativeTools);
1173
- this.server.sendLoggingMessage({
1174
- level: "info",
1175
- data: `Converted messages for MCP: ${JSON.stringify(messages)}`
1176
- });
1177
- let systemPrompt;
1178
- for (const msg of options.prompt) {
1179
- if (msg.role === "system") {
1180
- systemPrompt = msg.content;
1181
- break;
1182
- }
1183
- }
1184
- this.server.sendLoggingMessage({
1185
- level: "info",
1186
- data: `Client supports native tools: ${useNativeTools}`
1187
- });
1188
- systemPrompt = this.injectResponseFormatInstructions(systemPrompt, options.responseFormat, useNativeTools);
1189
- systemPrompt = this.injectToolInstructions(systemPrompt, options.tools, useNativeTools);
1190
- const createMessageParams = {
1191
- systemPrompt,
1192
- messages,
1193
- maxTokens: options.maxOutputTokens ?? this.maxTokens,
1194
- modelPreferences: this.modelPreferences
1195
- };
1196
- if (useNativeTools && options.tools && options.tools.length > 0) {
1197
- createMessageParams.tools = this.convertAISDKToolsToMCP(options.tools);
1198
- createMessageParams.toolChoice = {
1199
- mode: "auto"
1200
- };
1201
- this.server.sendLoggingMessage({
1202
- level: "info",
1203
- data: `Converted ${options.tools.length} tools to MCP format: ${JSON.stringify(createMessageParams.tools?.map((t) => t.name))}`
1204
- });
1205
- } else if (options.tools && options.tools.length > 0) {
1206
- this.server.sendLoggingMessage({
1207
- level: "info",
1208
- data: `Tools provided but not using native mode - injecting into system prompt instead`
1209
- });
1210
- }
1211
- this.server.sendLoggingMessage({
1212
- level: "info",
1213
- data: `Calling createMessage with params: ${JSON.stringify({
1214
- hasSystemPrompt: !!systemPrompt,
1215
- hasTools: !!createMessageParams.tools,
1216
- toolCount: createMessageParams.tools?.length || 0,
1217
- createMessageParams
1218
- }, null, 2)}`
1219
- });
1220
- const result = await this.server.createMessage(createMessageParams);
1221
- this.server.sendLoggingMessage({
1222
- level: "info",
1223
- data: `createMessage result: ${JSON.stringify({
1224
- contentType: result.content.type,
1225
- stopReason: result.stopReason,
1226
- text: result.content
1227
- })}`
1228
- });
1229
- const content = [];
1230
- if (useNativeTools) {
1231
- const contentArray = Array.isArray(result.content) ? result.content : [
1232
- result.content
1233
- ];
1234
- for (const block of contentArray) {
1235
- if (block.type === "text" && "text" in block) {
1236
- content.push({
1237
- type: "text",
1238
- text: block.text
1239
- });
1240
- } else if (block.type === "tool_use" && "id" in block && "name" in block) {
1241
- const toolInput = block.input || {};
1242
- content.push({
1243
- type: "tool-call",
1244
- toolCallId: block.id,
1245
- toolName: block.name,
1246
- input: JSON.stringify(toolInput)
1247
- });
1248
- }
1249
- }
1250
- } else {
1251
- if (result.content.type === "text" && result.content.text) {
1252
- const { text, toolCalls } = this.extractToolCalls(result.content.text, options.tools);
1253
- if (text.trim()) {
1254
- const textContent = {
1255
- type: "text",
1256
- text
1257
- };
1258
- content.push(textContent);
1259
- }
1260
- content.push(...toolCalls);
1261
- }
1262
- }
1263
- const finishReason = this.mapStopReason(result.stopReason);
1264
- return {
1265
- content,
1266
- finishReason,
1267
- usage: {
1268
- inputTokens: void 0,
1269
- outputTokens: void 0,
1270
- totalTokens: 0
1271
- },
1272
- request: {
1273
- body: JSON.stringify({
1274
- systemPrompt,
1275
- messages
1276
- })
1277
- },
1278
- response: {
1279
- modelId: result.model
1280
- },
1281
- warnings: []
1282
- };
1283
- }
1284
- /**
1285
- * Stream a response using MCP's createMessage capability
1286
- *
1287
- * Since MCP doesn't support native streaming, we generate the full response
1288
- * and emit it as stream events following AI SDK's protocol.
1289
- */
1290
- async doStream(options) {
1291
- const result = await this.doGenerate(options);
1292
- const stream = new ReadableStream({
1293
- start(controller) {
1294
- if (result.response?.modelId) {
1295
- controller.enqueue({
1296
- type: "response-metadata",
1297
- modelId: result.response.modelId,
1298
- ...result.response.headers && {
1299
- headers: result.response.headers
1300
- }
1301
- });
1302
- }
1303
- let textIndex = 0;
1304
- for (const part of result.content) {
1305
- if (part.type === "text") {
1306
- const id = `text-${++textIndex}`;
1307
- controller.enqueue({
1308
- type: "text-start",
1309
- id
1310
- });
1311
- controller.enqueue({
1312
- type: "text-delta",
1313
- id,
1314
- delta: part.text
1315
- });
1316
- controller.enqueue({
1317
- type: "text-end",
1318
- id
1319
- });
1320
- } else if (part.type === "tool-call") {
1321
- controller.enqueue({
1322
- type: "tool-call",
1323
- toolCallId: part.toolCallId,
1324
- toolName: part.toolName,
1325
- input: part.input
1326
- });
1327
- }
1328
- }
1329
- controller.enqueue({
1330
- type: "finish",
1331
- finishReason: result.finishReason,
1332
- usage: result.usage
1333
- });
1334
- controller.close();
1335
- }
1336
- });
1337
- return {
1338
- stream,
1339
- request: result.request,
1340
- warnings: result.warnings
1341
- };
1342
- }
1343
- /**
1344
- * Convert AI SDK messages to MCP sampling format
1345
- */
1346
- convertMessages(prompt, useNativeTools) {
1347
- if (!useNativeTools) {
1348
- return convertAISDKToMCPMessages(prompt);
1349
- }
1350
- const messages = [];
1351
- for (const msg of prompt) {
1352
- if (msg.role === "system") continue;
1353
- const role = msg.role === "assistant" ? "assistant" : "user";
1354
- const contentBlocks = [];
1355
- for (const part of msg.content) {
1356
- if (part.type === "text") {
1357
- contentBlocks.push({
1358
- type: "text",
1359
- text: part.text
1360
- });
1361
- } else if (part.type === "tool-call") {
1362
- const call = part;
1363
- contentBlocks.push({
1364
- type: "tool_use",
1365
- id: call.toolCallId,
1366
- name: call.toolName,
1367
- input: call.args ?? call.input ?? {}
1368
- });
1369
- } else if (part.type === "tool-result") {
1370
- const result = part;
1371
- contentBlocks.push({
1372
- type: "tool_result",
1373
- toolUseId: result.toolCallId,
1374
- // TODO: Handle different result types properly
1375
- content: [
1376
- {
1377
- type: "text",
1378
- text: result.output.type === "text" ? result.output.value?.toString() : JSON.stringify(result.output)
1379
- }
1380
- ]
1381
- });
1382
- }
1383
- }
1384
- if (contentBlocks.length > 0) {
1385
- messages.push({
1386
- role,
1387
- content: contentBlocks
1388
- });
1389
- }
1390
- }
1391
- return messages;
1392
- }
1393
- /**
1394
- * Map MCP stop reason to AI SDK finish reason
1395
- */
1396
- mapStopReason(stopReason) {
1397
- return convertMCPStopReasonToAISDK(stopReason);
1398
- }
1399
- /**
1400
- * Check if client supports native tool use in sampling
1401
- */
1402
- supportsSamplingTools() {
1403
- const capabilities = this.server.getClientCapabilities();
1404
- const supportsTools = !!capabilities?.sampling?.tools;
1405
- this.server.sendLoggingMessage({
1406
- level: "info",
1407
- data: `Client capabilities check: sampling=${!!capabilities?.sampling}, tools=${supportsTools}`
1408
- });
1409
- return supportsTools;
1410
- }
1411
- /**
1412
- * Convert AI SDK tools to MCP Tool format
1413
- */
1414
- convertAISDKToolsToMCP(tools) {
1415
- if (!tools || tools.length === 0) return [];
1416
- return tools.filter((tool2) => tool2.type === "function").map((tool2) => {
1417
- const toolAny = tool2;
1418
- return {
1419
- name: tool2.name,
1420
- description: toolAny.description || `Tool: ${tool2.name}`,
1421
- inputSchema: {
1422
- type: "object",
1423
- ...toolAny.inputSchema || toolAny.parameters
1424
- }
1425
- };
1426
- });
1427
- }
1428
- /**
1429
- * Inject response format instructions into system prompt
1430
- *
1431
- * Only injects formatting instructions in JSON fallback mode.
1432
- * In native tools mode, structured output is handled by the provider.
1433
- */
1434
- injectResponseFormatInstructions(systemPrompt, responseFormat, useNativeTools) {
1435
- if (!responseFormat) {
1436
- return systemPrompt;
1437
- }
1438
- if (useNativeTools) {
1439
- return systemPrompt;
1440
- }
1441
- let enhanced = systemPrompt || "";
1442
- if (responseFormat.type === "json") {
1443
- const jsonPrompt = `
1444
-
1445
- IMPORTANT: You MUST respond with valid JSON only. Do not include any text before or after the JSON.
1446
- - Your response must be a valid JSON object
1447
- - Do not wrap the JSON in markdown code blocks
1448
- - Do not include explanations or comments
1449
- - Ensure all JSON is properly formatted and parseable`;
1450
- enhanced = enhanced ? `${enhanced}${jsonPrompt}` : jsonPrompt.trim();
1451
- if (responseFormat.schema) {
1452
- const schemaInfo = `
1453
- - Follow this JSON schema structure: ${JSON.stringify(responseFormat.schema)}`;
1454
- enhanced += schemaInfo;
1455
- }
1456
- }
1457
- return enhanced || void 0;
1458
- }
1459
- /**
1460
- * Inject tool definitions into system prompt
1461
- *
1462
- * WORKAROUND: MCP sampling currently doesn't support native tools parameter.
1463
- * This method injects tool descriptions and usage instructions into the system prompt.
1464
- *
1465
- * TODO: Remove this workaround when MCP protocol adds native support for:
1466
- * - tools parameter in createMessage
1467
- * - Tool calling and function execution
1468
- * - Structured tool responses
1469
- */
1470
- injectToolInstructions(systemPrompt, tools, useNativeTools) {
1471
- if (!tools || tools.length === 0) {
1472
- return systemPrompt;
1473
- }
1474
- if (useNativeTools) {
1475
- this.server.sendLoggingMessage({
1476
- level: "info",
1477
- data: `Using native tools mode - skipping XML tool injection`
1478
- });
1479
- return systemPrompt;
1480
- }
1481
- this.server.sendLoggingMessage({
1482
- level: "info",
1483
- data: `Injecting ${tools.length} tools into system prompt (fallback mode)`
1484
- });
1485
- let enhanced = systemPrompt || "";
1486
- const toolsPrompt = `
1487
-
1488
- <available_tools>
1489
- You have access to the following tools. To use a tool, respond with this XML format:
1490
- <use_tool tool="tool_name">
1491
- {"param1": "value1", "param2": "value2"}
1492
- </use_tool>
1493
-
1494
- Follow the JSON schema definition for each tool's parameters.
1495
- You can use multiple tools in one response. DO NOT include text before or after tool calls - wait for the tool results first.
1496
-
1497
- <tools>`;
1498
- const toolDescriptions = tools.map((tool2) => {
1499
- if (tool2.type === "function") {
1500
- const toolAny = tool2;
1501
- const description = toolAny.description || "No description provided";
1502
- const schema = toolAny.inputSchema || toolAny.parameters;
1503
- const schemaStr = schema ? `
1504
- <schema>
1505
- ${JSON.stringify(schema, null, 2)}
1506
- </schema>` : "";
1507
- return `
1508
- <tool name="${tool2.name}">
1509
- <description>
1510
- ${description}
1511
- </description>${schemaStr}
1512
- </tool>`;
1513
- } else if (tool2.type === "provider-defined") {
1514
- return `
1515
- <tool name="${tool2.name}">
1516
- <description>${tool2.id || "No description provided"}</description>
1517
- </tool>`;
1518
- }
1519
- return "";
1520
- }).filter(Boolean).join("");
1521
- const toolsEnd = `
1522
- </tools>
1523
- </available_tools>`;
1524
- enhanced = enhanced ? `${enhanced}${toolsPrompt}${toolDescriptions}${toolsEnd}` : `${toolsPrompt}${toolDescriptions}${toolsEnd}`.trim();
1525
- return enhanced || void 0;
1526
- }
1527
- /**
1528
- * Extract tool calls from LLM response text
1529
- *
1530
- * Parses XML-style tool call tags from the response:
1531
- * <use_tool tool="tool_name">{"arg": "value"}</use_tool>
1532
- */
1533
- extractToolCalls(responseText, tools) {
1534
- if (!tools || tools.length === 0) {
1535
- return {
1536
- text: responseText,
1537
- toolCalls: []
1538
- };
1539
- }
1540
- const toolCalls = [];
1541
- const toolCallRegex = /<use_tool\s+tool="([^"]+)">([\s\S]*?)<\/use_tool>/g;
1542
- let match;
1543
- let lastIndex = 0;
1544
- const textParts = [];
1545
- let callIndex = 0;
1546
- while ((match = toolCallRegex.exec(responseText)) !== null) {
1547
- textParts.push(responseText.slice(lastIndex, match.index));
1548
- const toolName = match[1];
1549
- const argsText = match[2].trim?.();
1550
- toolCalls.push({
1551
- type: "tool-call",
1552
- toolCallId: `call_${Date.now()}_${callIndex++}`,
1553
- toolName,
1554
- input: argsText
1555
- });
1556
- lastIndex = match.index + match[0].length;
1557
- }
1558
- textParts.push(responseText.slice(lastIndex));
1559
- const text = textParts.join("").trim();
1560
- return {
1561
- text,
1562
- toolCalls
1563
- };
1564
- }
1565
- };
1566
-
1567
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/provider.js
1568
- var MCPSamplingProvider = class {
1569
- config;
1570
- constructor(config) {
1571
- this.config = config;
1572
- }
1573
- /**
1574
- * Create a language model instance for a specific MCP tool/agent
1575
- *
1576
- * @param options - Optional configuration overrides
1577
- * @returns A LanguageModelV2 instance
1578
- */
1579
- languageModel(options) {
1580
- return new MCPSamplingLanguageModel({
1581
- server: this.config.server,
1582
- modelPreferences: options?.modelPreferences,
1583
- maxTokens: this.config.maxTokens
1584
- });
1585
- }
1586
- /**
1587
- * Shorthand for creating a language model
1588
- */
1589
- call(options) {
1590
- return this.languageModel(options);
1591
- }
1592
- };
1593
-
1594
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/client-sampling.js
1595
- import { CreateMessageRequestSchema } from "@modelcontextprotocol/sdk/types.js";
1596
-
1597
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/base-ai-executor.js
1598
- import { trace as trace2 } from "@opentelemetry/api";
1599
- import { jsonSchema as jsonSchema2, stepCountIs, streamText, tool } from "ai";
1600
- var BaseAIExecutor = class {
1601
- config;
1602
- tracer;
1603
- logger;
1604
- constructor(config, server) {
1605
- this.config = {
1606
- maxSteps: 50,
1607
- tracingEnabled: true,
1608
- ...config
1609
- };
1610
- this.tracer = trace2.getTracer(`mcpc.ai.${config.name}`);
1611
- this.logger = createLogger(`mcpc.ai.${config.name}`, server);
1612
- }
1613
- execute(args) {
1614
- if (this.config.tracingEnabled) {
1615
- return this.executeWithTracing(args);
1616
- }
1617
- return this.executeCore(args);
1618
- }
1619
- executeWithTracing(args) {
1620
- return this.tracer.startActiveSpan(`mcpc.ai.${this.config.name}`, async (span) => {
1621
- try {
1622
- span.setAttributes({
1623
- "mcpc.executor": this.config.name,
1624
- "mcpc.type": this.getExecutorType()
1625
- });
1626
- const result = await this.executeCore(args, span);
1627
- span.setAttributes({
1628
- "mcpc.error": !!result.isError
1629
- });
1630
- return result;
1631
- } catch (error) {
1632
- span.recordException(error);
1633
- throw error;
1634
- } finally {
1635
- span.end();
1636
- }
1637
- });
1638
- }
1639
- async executeCore(args, span) {
1640
- try {
1641
- const result = streamText({
1642
- model: this.getModel(),
1643
- system: this.buildSystemPrompt(args),
1644
- messages: [
1645
- {
1646
- role: "user",
1647
- content: args.prompt
1648
- }
1649
- ],
1650
- tools: this.buildTools(),
1651
- stopWhen: stepCountIs(this.config.maxSteps),
1652
- experimental_telemetry: this.config.tracingEnabled ? {
1653
- isEnabled: true,
1654
- functionId: `mcpc.${this.config.name}`,
1655
- tracer: this.tracer
1656
- } : void 0,
1657
- onStepFinish: (step) => {
1658
- if (span) {
1659
- span.addEvent("step", {
1660
- tools: step.toolCalls?.length ?? 0,
1661
- reason: step.finishReason ?? ""
1662
- });
1663
- }
1664
- }
1665
- });
1666
- return {
1667
- content: [
1668
- {
1669
- type: "text",
1670
- text: await result.text || `Completed in ${(await result.steps)?.length ?? "unknown"} step(s).`
1671
- }
1672
- ],
1673
- isError: false
1674
- };
1675
- } catch (error) {
1676
- this.logger.error({
1677
- message: "Execution error",
1678
- error
1679
- });
1680
- return {
1681
- content: [
1682
- {
1683
- type: "text",
1684
- text: `Error: ${error instanceof Error ? error.message : String(error)}`
1685
- }
1686
- ],
1687
- isError: true
1688
- };
1689
- }
1690
- }
1691
- buildSystemPrompt(args) {
1692
- return CompiledPrompts.aiLoopSystem({
1693
- toolName: this.config.name,
1694
- description: this.config.description,
1695
- rules: this.getRules(),
1696
- context: this.formatContext(args.context)
1697
- });
1698
- }
1699
- getRules() {
1700
- return `1. Use tools to complete the user's request
1701
- 2. Review results after each tool call
1702
- 3. Adapt your approach based on outcomes
1703
- 4. Continue until task is complete
1704
- 5. When complete, provide a summary WITHOUT calling more tools`;
1705
- }
1706
- formatContext(context2) {
1707
- if (!context2 || Object.keys(context2).length === 0) {
1708
- return "";
1709
- }
1710
- return `
1711
-
1712
- <context>
1713
- ${JSON.stringify(context2, null, 2)}
1714
- </context>`;
1715
- }
1716
- convertToAISDKTool(name, toolDetail, execute) {
1717
- const cleanedSchema = toolDetail.inputSchema ? cleanToolSchema(toolDetail.inputSchema) : {
1718
- type: "object"
1719
- };
1720
- return tool({
1721
- description: toolDetail.description || `Tool: ${name}`,
1722
- inputSchema: jsonSchema2(cleanedSchema),
1723
- execute
1724
- });
1725
- }
1726
- };
1727
-
1728
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-executor.js
1729
- var AISamplingExecutor = class extends BaseAIExecutor {
1730
- server;
1731
- tools;
1732
- providerOptions;
1733
- maxTokens;
1734
- model = null;
1735
- constructor(config) {
1736
- super(config, "callTool" in config.server ? config.server : void 0);
1737
- this.server = config.server;
1738
- this.tools = config.tools;
1739
- this.providerOptions = config.providerOptions;
1740
- this.maxTokens = config.maxTokens;
1741
- }
1742
- initProvider() {
1743
- if (!this.model) {
1744
- const provider = new MCPSamplingProvider({
1745
- server: this.server,
1746
- maxTokens: this.maxTokens
1747
- });
1748
- this.model = provider.languageModel(this.providerOptions);
1749
- }
1750
- return this.model;
1751
- }
1752
- getModel() {
1753
- if (!this.model) throw new Error("Model not initialized");
1754
- return this.model;
1755
- }
1756
- getExecutorType() {
1757
- return "mcp";
1758
- }
1759
- buildTools() {
1760
- const aiTools = {};
1761
- for (const [name, detail] of this.tools) {
1762
- aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
1763
- const result = await this.callTool(name, input);
1764
- return this.formatResult(result);
1765
- });
1766
- }
1767
- return aiTools;
1768
- }
1769
- async callTool(name, input) {
1770
- if ("callTool" in this.server) {
1771
- return await this.server.callTool(name, input);
1772
- }
1773
- const detail = this.tools.find(([n]) => n === name)?.[1];
1774
- if (detail?.execute) return await detail.execute(input);
1775
- throw new Error(`Cannot call tool "${name}"`);
1776
- }
1777
- formatResult(result) {
1778
- const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
1779
- return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
1780
- }
1781
- execute(args) {
1782
- this.initProvider();
1783
- return super.execute(args);
1784
- }
1785
- };
1786
-
1787
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-registrar.js
1788
- function registerAISamplingTool(server, params) {
1789
- const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false, maxTokens } = params;
1790
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1791
- const executor = new AISamplingExecutor({
1792
- name,
1793
- description,
1794
- server,
1795
- tools: toolNameToDetailList,
1796
- providerOptions,
1797
- maxSteps,
1798
- tracingEnabled,
1799
- maxTokens
1800
- });
1801
- const toolDescription = CompiledPrompts.samplingToolDescription({
1802
- toolName: name,
1803
- description,
1804
- toolList: allToolNames.map((n) => `- ${n}`).join("\n")
1805
- });
1806
- const argsDef = createArgsDef.forSampling();
1807
- const schema = allToolNames.length > 0 ? argsDef : {
1808
- type: "object",
1809
- properties: {}
1810
- };
1811
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
1812
- const validationResult = validateSchema(args, schema);
1813
- if (!validationResult.valid) {
1814
- return {
1815
- content: [
1816
- {
1817
- type: "text",
1818
- text: CompiledPrompts.errorResponse({
1819
- errorMessage: validationResult.error || "Validation failed"
1820
- })
1821
- }
1822
- ],
1823
- isError: true
1824
- };
1825
- }
1826
- const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
1827
- return executor.execute({
1828
- prompt,
1829
- context: args.context
1830
- });
1831
- });
1832
- }
1833
-
1834
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-sampling-plugin.js
1835
- var createAISamplingModePlugin = () => ({
1836
- name: "mode-ai-sampling",
1837
- version: "1.0.0",
1838
- apply: "ai_sampling",
1839
- registerAgentTool: (context2) => {
1840
- const opts = context2.options;
1841
- registerAISamplingTool(context2.server, {
1842
- description: context2.description,
1843
- name: context2.name,
1844
- allToolNames: context2.allToolNames,
1845
- depGroups: context2.depGroups,
1846
- toolNameToDetailList: context2.toolNameToDetailList,
1847
- providerOptions: opts.providerOptions,
1848
- maxSteps: opts.maxSteps,
1849
- tracingEnabled: opts.tracingEnabled,
1850
- maxTokens: opts.maxTokens
1851
- });
1852
- }
1853
- });
1854
- var mode_ai_sampling_plugin_default = createAISamplingModePlugin();
1855
-
1856
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
1857
- import { acpTools, createACPProvider } from "@mcpc-tech/acp-ai-provider";
1858
- var AIACPExecutor = class extends BaseAIExecutor {
1859
- acpSettings;
1860
- tools;
1861
- provider = null;
1862
- model = null;
1863
- constructor(config) {
1864
- super(config);
1865
- this.acpSettings = config.acpSettings;
1866
- this.tools = config.tools;
1867
- }
1868
- initProvider() {
1869
- if (!this.model) {
1870
- this.provider = createACPProvider(this.acpSettings);
1871
- this.model = this.provider.languageModel();
1872
- }
1873
- return this.model;
1874
- }
1875
- getModel() {
1876
- if (!this.model) throw new Error("Model not initialized");
1877
- return this.model;
1878
- }
1879
- getExecutorType() {
1880
- return "acp";
1881
- }
1882
- buildTools() {
1883
- const aiTools = {};
1884
- for (const [name, detail] of this.tools) {
1885
- if (!detail.execute) continue;
1886
- aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
1887
- const result = await detail.execute(input);
1888
- return this.formatResult(result);
1889
- });
1890
- }
1891
- return acpTools(aiTools);
1892
- }
1893
- formatResult(result) {
1894
- const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
1895
- return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
1896
- }
1897
- execute(args) {
1898
- this.initProvider();
1899
- return super.execute(args);
1900
- }
1901
- cleanup() {
1902
- if (this.provider && typeof this.provider.cleanup === "function") {
1903
- this.provider.cleanup();
1904
- }
1905
- this.model = null;
1906
- this.provider = null;
1907
- }
1908
- };
1909
-
1910
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-registrar.js
1911
- function registerAIACPTool(server, params) {
1912
- const { name, description, allToolNames, depGroups, toolNameToDetailList, acpSettings, maxSteps = 50, tracingEnabled = false } = params;
1913
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1914
- const executor = new AIACPExecutor({
1915
- name,
1916
- description,
1917
- acpSettings,
1918
- tools: toolNameToDetailList,
1919
- maxSteps,
1920
- tracingEnabled
1921
- });
1922
- const toolDescription = CompiledPrompts.samplingToolDescription({
1923
- toolName: name,
1924
- description,
1925
- toolList: allToolNames.length > 0 ? allToolNames.map((n) => `- ${n}`).join("\n") : "Agent has its own tools"
1926
- });
1927
- const argsDef = createArgsDef.forSampling();
1928
- const schema = allToolNames.length > 0 ? argsDef : {
1929
- type: "object",
1930
- properties: {}
1931
- };
1932
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
1933
- const validationResult = validateSchema(args, schema);
1934
- if (!validationResult.valid) {
1935
- return {
1936
- content: [
1937
- {
1938
- type: "text",
1939
- text: CompiledPrompts.errorResponse({
1940
- errorMessage: validationResult.error || "Validation failed"
1941
- })
1942
- }
1943
- ],
1944
- isError: true
1945
- };
1946
- }
1947
- const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
1948
- return executor.execute({
1949
- prompt,
1950
- context: args.context
1951
- });
1952
- });
1953
- return executor;
1954
- }
1955
-
1956
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-acp-plugin.js
1957
- var createAIACPModePlugin = () => ({
1958
- name: "mode-ai-acp",
1959
- version: "1.0.0",
1960
- apply: "ai_acp",
1961
- registerAgentTool: (context2) => {
1962
- const opts = context2.options;
1963
- if (!opts.acpSettings) {
1964
- throw new Error("ai_acp mode requires acpSettings in options");
1965
- }
1966
- registerAIACPTool(context2.server, {
1967
- description: context2.description,
1968
- name: context2.name,
1969
- allToolNames: context2.allToolNames,
1970
- depGroups: context2.depGroups,
1971
- toolNameToDetailList: context2.toolNameToDetailList,
1972
- acpSettings: opts.acpSettings,
1973
- maxSteps: opts.maxSteps,
1974
- tracingEnabled: opts.tracingEnabled
1975
- });
1976
- }
1977
- });
1978
- var mode_ai_acp_plugin_default = createAIACPModePlugin();
1979
-
1980
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
1981
- import traverse from "json-schema-traverse";
1982
-
1983
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
1984
- import process4 from "node:process";
1985
- var isSCF = () => Boolean(process4.env.SCF_RUNTIME || process4.env.PROD_SCF);
1986
- if (isSCF()) {
1987
- console.log({
1988
- isSCF: isSCF(),
1989
- SCF_RUNTIME: process4.env.SCF_RUNTIME
1990
- });
1991
- }
1992
-
1993
- // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
1994
- var markdownAgentLoader = null;
1995
- function setMarkdownAgentLoader(loader) {
1996
- markdownAgentLoader = loader;
1997
- }
1998
- function isMarkdownFile(path) {
1999
- return path.endsWith(".md") || path.endsWith(".markdown");
2000
- }
2001
-
2002
5
  // __mcpc__plugin-markdown-loader_latest/node_modules/@mcpc/plugin-markdown-loader/src/markdown-loader.js
2003
6
  import { readdir, readFile, stat } from "node:fs/promises";
2004
7
 
@@ -3940,10 +1943,13 @@ function parse(content, options = {}) {
3940
1943
 
3941
1944
  // __mcpc__plugin-markdown-loader_latest/node_modules/@mcpc/plugin-markdown-loader/src/markdown-loader.js
3942
1945
  import { join } from "node:path";
3943
- import process5 from "node:process";
1946
+ import process from "node:process";
1947
+ function isMarkdownFile(path) {
1948
+ return path.endsWith(".md") || path.endsWith(".markdown");
1949
+ }
3944
1950
  function replaceEnvVars(str2) {
3945
1951
  return str2.replace(/\$([A-Za-z_][A-Za-z0-9_]*)(?!\s*\()/g, (match, varName) => {
3946
- const value = process5.env[varName];
1952
+ const value = process.env[varName];
3947
1953
  if (value !== void 0) {
3948
1954
  return value;
3949
1955
  }
@@ -4072,8 +2078,9 @@ function markdownLoaderPlugin() {
4072
2078
  version: "1.0.0",
4073
2079
  enforce: "pre",
4074
2080
  // Run before other plugins
4075
- configureServer: () => {
4076
- setMarkdownAgentLoader(loadMarkdownAgentFile);
2081
+ configureServer: (server) => {
2082
+ server.registerFileLoader(".md", loadMarkdownAgentFile);
2083
+ server.registerFileLoader(".markdown", loadMarkdownAgentFile);
4077
2084
  }
4078
2085
  };
4079
2086
  }
@@ -4089,6 +2096,5 @@ export {
4089
2096
  loadMarkdownAgentFile,
4090
2097
  markdownAgentToComposeDefinition,
4091
2098
  markdownLoaderPlugin,
4092
- parseMarkdownAgent,
4093
- setMarkdownAgentLoader
2099
+ parseMarkdownAgent
4094
2100
  };