opc-agent 0.7.0 → 0.8.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/channels/email.d.ts +69 -0
- package/dist/channels/email.js +118 -0
- package/dist/channels/slack.d.ts +62 -0
- package/dist/channels/slack.js +107 -0
- package/dist/channels/wechat.d.ts +62 -0
- package/dist/channels/wechat.js +104 -0
- package/dist/core/compose.d.ts +35 -0
- package/dist/core/compose.js +49 -0
- package/dist/core/orchestrator.d.ts +68 -0
- package/dist/core/orchestrator.js +145 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +22 -1
- package/dist/tools/calculator.d.ts +7 -0
- package/dist/tools/calculator.js +70 -0
- package/dist/tools/datetime.d.ts +7 -0
- package/dist/tools/datetime.js +159 -0
- package/dist/tools/json-transform.d.ts +7 -0
- package/dist/tools/json-transform.js +184 -0
- package/dist/tools/text-analysis.d.ts +8 -0
- package/dist/tools/text-analysis.js +113 -0
- package/package.json +1 -1
- package/src/channels/email.ts +177 -0
- package/src/channels/slack.ts +160 -0
- package/src/channels/wechat.ts +149 -0
- package/src/core/compose.ts +77 -0
- package/src/core/orchestrator.ts +215 -0
- package/src/index.ts +16 -0
- package/src/tools/calculator.ts +73 -0
- package/src/tools/datetime.ts +149 -0
- package/src/tools/json-transform.ts +187 -0
- package/src/tools/text-analysis.ts +116 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import type { AgentContext, Message } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Multi-Agent Orchestrator — v0.8.0
|
|
6
|
+
* Routes messages to specialized sub-agents, supports parallel execution and handoffs.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface AgentNode {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
description: string;
|
|
13
|
+
/** Patterns or intents this agent handles */
|
|
14
|
+
routes: string[];
|
|
15
|
+
/** Function that processes a message and returns a response */
|
|
16
|
+
handler: (context: AgentContext, message: Message) => Promise<Message>;
|
|
17
|
+
/** Priority for routing conflicts (higher wins) */
|
|
18
|
+
priority?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface OrchestratorWorkflow {
|
|
22
|
+
name: string;
|
|
23
|
+
description?: string;
|
|
24
|
+
/** Ordered list of agent IDs for sequential execution */
|
|
25
|
+
steps?: string[];
|
|
26
|
+
/** List of agent IDs for parallel execution */
|
|
27
|
+
parallel?: string[];
|
|
28
|
+
/** Router config: auto-route based on message content */
|
|
29
|
+
router?: {
|
|
30
|
+
agents: string[];
|
|
31
|
+
fallback?: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface HandoffRequest {
|
|
36
|
+
fromAgent: string;
|
|
37
|
+
toAgent: string;
|
|
38
|
+
context: AgentContext;
|
|
39
|
+
reason: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface OrchestratorConfig {
|
|
43
|
+
agents: AgentNode[];
|
|
44
|
+
workflows?: OrchestratorWorkflow[];
|
|
45
|
+
defaultWorkflow?: string;
|
|
46
|
+
maxParallel?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class Orchestrator extends EventEmitter {
|
|
50
|
+
private agents: Map<string, AgentNode> = new Map();
|
|
51
|
+
private workflows: Map<string, OrchestratorWorkflow> = new Map();
|
|
52
|
+
private defaultWorkflow?: string;
|
|
53
|
+
private maxParallel: number;
|
|
54
|
+
|
|
55
|
+
constructor(config: OrchestratorConfig) {
|
|
56
|
+
super();
|
|
57
|
+
this.maxParallel = config.maxParallel ?? 5;
|
|
58
|
+
this.defaultWorkflow = config.defaultWorkflow;
|
|
59
|
+
|
|
60
|
+
for (const agent of config.agents) {
|
|
61
|
+
this.agents.set(agent.id, agent);
|
|
62
|
+
}
|
|
63
|
+
for (const wf of config.workflows ?? []) {
|
|
64
|
+
this.workflows.set(wf.name, wf);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Register a new agent node */
|
|
69
|
+
registerAgent(agent: AgentNode): void {
|
|
70
|
+
this.agents.set(agent.id, agent);
|
|
71
|
+
this.emit('agent:registered', agent.id);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Unregister an agent */
|
|
75
|
+
unregisterAgent(id: string): void {
|
|
76
|
+
this.agents.delete(id);
|
|
77
|
+
this.emit('agent:unregistered', id);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Route a message to the best-matching agent */
|
|
81
|
+
route(message: Message): AgentNode | undefined {
|
|
82
|
+
const content = message.content.toLowerCase();
|
|
83
|
+
let bestMatch: AgentNode | undefined;
|
|
84
|
+
let bestPriority = -1;
|
|
85
|
+
|
|
86
|
+
for (const agent of this.agents.values()) {
|
|
87
|
+
for (const route of agent.routes) {
|
|
88
|
+
if (content.includes(route.toLowerCase()) || new RegExp(route, 'i').test(content)) {
|
|
89
|
+
const priority = agent.priority ?? 0;
|
|
90
|
+
if (priority > bestPriority) {
|
|
91
|
+
bestMatch = agent;
|
|
92
|
+
bestPriority = priority;
|
|
93
|
+
}
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return bestMatch;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Execute a single agent */
|
|
102
|
+
async executeAgent(agentId: string, context: AgentContext, message: Message): Promise<Message> {
|
|
103
|
+
const agent = this.agents.get(agentId);
|
|
104
|
+
if (!agent) throw new Error(`Agent not found: ${agentId}`);
|
|
105
|
+
this.emit('agent:execute', agentId, message);
|
|
106
|
+
const result = await agent.handler(context, message);
|
|
107
|
+
this.emit('agent:complete', agentId, result);
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Run multiple agents in parallel */
|
|
112
|
+
async executeParallel(
|
|
113
|
+
agentIds: string[],
|
|
114
|
+
context: AgentContext,
|
|
115
|
+
message: Message
|
|
116
|
+
): Promise<Map<string, Message>> {
|
|
117
|
+
const results = new Map<string, Message>();
|
|
118
|
+
const batches: string[][] = [];
|
|
119
|
+
|
|
120
|
+
// Batch by maxParallel
|
|
121
|
+
for (let i = 0; i < agentIds.length; i += this.maxParallel) {
|
|
122
|
+
batches.push(agentIds.slice(i, i + this.maxParallel));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
for (const batch of batches) {
|
|
126
|
+
const promises = batch.map(async (id) => {
|
|
127
|
+
const result = await this.executeAgent(id, context, message);
|
|
128
|
+
results.set(id, result);
|
|
129
|
+
});
|
|
130
|
+
await Promise.all(promises);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return results;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Execute a named workflow */
|
|
137
|
+
async executeWorkflow(
|
|
138
|
+
workflowName: string,
|
|
139
|
+
context: AgentContext,
|
|
140
|
+
message: Message
|
|
141
|
+
): Promise<Message[]> {
|
|
142
|
+
const wf = this.workflows.get(workflowName);
|
|
143
|
+
if (!wf) throw new Error(`Workflow not found: ${workflowName}`);
|
|
144
|
+
|
|
145
|
+
const results: Message[] = [];
|
|
146
|
+
|
|
147
|
+
// Sequential steps
|
|
148
|
+
if (wf.steps) {
|
|
149
|
+
let currentMessage = message;
|
|
150
|
+
for (const agentId of wf.steps) {
|
|
151
|
+
const result = await this.executeAgent(agentId, context, currentMessage);
|
|
152
|
+
results.push(result);
|
|
153
|
+
currentMessage = result; // chain output → next input
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Parallel execution
|
|
158
|
+
if (wf.parallel) {
|
|
159
|
+
const parallelResults = await this.executeParallel(wf.parallel, context, message);
|
|
160
|
+
results.push(...parallelResults.values());
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Router-based
|
|
164
|
+
if (wf.router) {
|
|
165
|
+
const matched = this.route(message);
|
|
166
|
+
const targetId = matched && wf.router.agents.includes(matched.id)
|
|
167
|
+
? matched.id
|
|
168
|
+
: wf.router.fallback;
|
|
169
|
+
if (targetId) {
|
|
170
|
+
const result = await this.executeAgent(targetId, context, message);
|
|
171
|
+
results.push(result);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return results;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Hand off conversation from one agent to another */
|
|
179
|
+
async handoff(request: HandoffRequest): Promise<Message> {
|
|
180
|
+
this.emit('agent:handoff', request);
|
|
181
|
+
const { toAgent, context } = request;
|
|
182
|
+
const lastMessage = context.messages[context.messages.length - 1];
|
|
183
|
+
if (!lastMessage) throw new Error('No message in context for handoff');
|
|
184
|
+
return this.executeAgent(toAgent, context, lastMessage);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Process an incoming message using the default workflow or routing */
|
|
188
|
+
async process(context: AgentContext, message: Message): Promise<Message[]> {
|
|
189
|
+
if (this.defaultWorkflow) {
|
|
190
|
+
return this.executeWorkflow(this.defaultWorkflow, context, message);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Fallback: route to single agent
|
|
194
|
+
const agent = this.route(message);
|
|
195
|
+
if (agent) {
|
|
196
|
+
const result = await this.executeAgent(agent.id, context, message);
|
|
197
|
+
return [result];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return [{
|
|
201
|
+
id: `orch-${Date.now()}`,
|
|
202
|
+
role: 'assistant',
|
|
203
|
+
content: 'No agent available to handle this request.',
|
|
204
|
+
timestamp: Date.now(),
|
|
205
|
+
}];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
getAgents(): AgentNode[] {
|
|
209
|
+
return Array.from(this.agents.values());
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
getWorkflows(): OrchestratorWorkflow[] {
|
|
213
|
+
return Array.from(this.workflows.values());
|
|
214
|
+
}
|
|
215
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -58,6 +58,22 @@ export type { AgentManifest, PublishOptions, InstallOptions } from './marketplac
|
|
|
58
58
|
// v0.7.0 modules
|
|
59
59
|
export { createAuthMiddleware, getActiveSessions } from './core/auth';
|
|
60
60
|
export type { AuthConfig, AuthSession } from './core/auth';
|
|
61
|
+
// v0.8.0 modules
|
|
62
|
+
export { Orchestrator } from './core/orchestrator';
|
|
63
|
+
export type { AgentNode, OrchestratorWorkflow, OrchestratorConfig, HandoffRequest } from './core/orchestrator';
|
|
64
|
+
export { AgentPipeline, compose } from './core/compose';
|
|
65
|
+
export type { ComposableAgent, ComposeOptions } from './core/compose';
|
|
66
|
+
export { EmailChannel } from './channels/email';
|
|
67
|
+
export type { EmailChannelConfig, EmailMessage } from './channels/email';
|
|
68
|
+
export { SlackChannel } from './channels/slack';
|
|
69
|
+
export type { SlackChannelConfig, SlashCommandConfig, SlashCommandPayload } from './channels/slack';
|
|
70
|
+
export { WeChatChannel } from './channels/wechat';
|
|
71
|
+
export type { WeChatChannelConfig, WeChatMessage, TemplateMessageData } from './channels/wechat';
|
|
72
|
+
export { CalculatorTool } from './tools/calculator';
|
|
73
|
+
export { DateTimeTool } from './tools/datetime';
|
|
74
|
+
export { JsonTransformTool } from './tools/json-transform';
|
|
75
|
+
export { TextAnalysisTool } from './tools/text-analysis';
|
|
76
|
+
|
|
61
77
|
export { HttpSkill } from './skills/http';
|
|
62
78
|
export { WebhookTriggerSkill } from './skills/webhook-trigger';
|
|
63
79
|
export type { WebhookTarget } from './skills/webhook-trigger';
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { MCPTool, MCPToolResult } from './mcp';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Calculator Tool — v0.8.0
|
|
5
|
+
* Safe math expression evaluation as an LLM function tool.
|
|
6
|
+
*/
|
|
7
|
+
export const CalculatorTool: MCPTool = {
|
|
8
|
+
name: 'calculator',
|
|
9
|
+
description: 'Evaluate a mathematical expression. Supports basic arithmetic, powers, sqrt, abs, min, max, round, ceil, floor, PI, E.',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
type: 'object',
|
|
12
|
+
properties: {
|
|
13
|
+
expression: {
|
|
14
|
+
type: 'string',
|
|
15
|
+
description: 'Mathematical expression to evaluate, e.g. "2 + 3 * 4" or "sqrt(144) + PI"',
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
required: ['expression'],
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
async execute(input: Record<string, unknown>): Promise<MCPToolResult> {
|
|
22
|
+
const expr = String(input.expression ?? '');
|
|
23
|
+
try {
|
|
24
|
+
const result = safeEval(expr);
|
|
25
|
+
return { content: String(result) };
|
|
26
|
+
} catch (err) {
|
|
27
|
+
return { content: `Error: ${(err as Error).message}`, isError: true };
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Safe math evaluator — no eval(), no arbitrary code */
|
|
33
|
+
function safeEval(expr: string): number {
|
|
34
|
+
// Whitelist: digits, operators, parens, dots, commas, spaces, and known functions
|
|
35
|
+
const sanitized = expr.replace(/\s+/g, '');
|
|
36
|
+
const allowed = /^[0-9+\-*/().,%^a-zA-Z_]+$/;
|
|
37
|
+
if (!allowed.test(sanitized)) {
|
|
38
|
+
throw new Error('Invalid characters in expression');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Replace known math functions/constants
|
|
42
|
+
const prepared = sanitized
|
|
43
|
+
.replace(/\bPI\b/gi, String(Math.PI))
|
|
44
|
+
.replace(/\bE\b/g, String(Math.E))
|
|
45
|
+
.replace(/\bsqrt\b/gi, 'Math.sqrt')
|
|
46
|
+
.replace(/\babs\b/gi, 'Math.abs')
|
|
47
|
+
.replace(/\bmin\b/gi, 'Math.min')
|
|
48
|
+
.replace(/\bmax\b/gi, 'Math.max')
|
|
49
|
+
.replace(/\bround\b/gi, 'Math.round')
|
|
50
|
+
.replace(/\bceil\b/gi, 'Math.ceil')
|
|
51
|
+
.replace(/\bfloor\b/gi, 'Math.floor')
|
|
52
|
+
.replace(/\bpow\b/gi, 'Math.pow')
|
|
53
|
+
.replace(/\blog\b/gi, 'Math.log')
|
|
54
|
+
.replace(/\blog10\b/gi, 'Math.log10')
|
|
55
|
+
.replace(/\bsin\b/gi, 'Math.sin')
|
|
56
|
+
.replace(/\bcos\b/gi, 'Math.cos')
|
|
57
|
+
.replace(/\btan\b/gi, 'Math.tan')
|
|
58
|
+
.replace(/\^/g, '**');
|
|
59
|
+
|
|
60
|
+
// Block anything that isn't math
|
|
61
|
+
if (/[a-zA-Z_]/.test(prepared.replace(/Math\.\w+/g, ''))) {
|
|
62
|
+
throw new Error('Unsupported function or variable in expression');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Use Function constructor with restricted scope
|
|
66
|
+
const fn = new Function('Math', `"use strict"; return (${prepared});`);
|
|
67
|
+
const result = fn(Math);
|
|
68
|
+
|
|
69
|
+
if (typeof result !== 'number' || !isFinite(result)) {
|
|
70
|
+
throw new Error('Expression did not evaluate to a finite number');
|
|
71
|
+
}
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { MCPTool, MCPToolResult } from './mcp';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* DateTime Tool — v0.8.0
|
|
5
|
+
* Date/time operations as an LLM function tool.
|
|
6
|
+
*/
|
|
7
|
+
export const DateTimeTool: MCPTool = {
|
|
8
|
+
name: 'datetime',
|
|
9
|
+
description: 'Get current date/time, format dates, calculate date differences, or add/subtract time.',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
type: 'object',
|
|
12
|
+
properties: {
|
|
13
|
+
operation: {
|
|
14
|
+
type: 'string',
|
|
15
|
+
enum: ['now', 'format', 'diff', 'add', 'parse'],
|
|
16
|
+
description: 'Operation to perform',
|
|
17
|
+
},
|
|
18
|
+
date: {
|
|
19
|
+
type: 'string',
|
|
20
|
+
description: 'Date string (ISO 8601 or common format)',
|
|
21
|
+
},
|
|
22
|
+
date2: {
|
|
23
|
+
type: 'string',
|
|
24
|
+
description: 'Second date for diff operation',
|
|
25
|
+
},
|
|
26
|
+
format: {
|
|
27
|
+
type: 'string',
|
|
28
|
+
description: 'Output format: iso, date, time, datetime, unix, relative',
|
|
29
|
+
},
|
|
30
|
+
amount: {
|
|
31
|
+
type: 'number',
|
|
32
|
+
description: 'Amount to add (can be negative)',
|
|
33
|
+
},
|
|
34
|
+
unit: {
|
|
35
|
+
type: 'string',
|
|
36
|
+
enum: ['milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'],
|
|
37
|
+
description: 'Unit for add operation',
|
|
38
|
+
},
|
|
39
|
+
timezone: {
|
|
40
|
+
type: 'string',
|
|
41
|
+
description: 'IANA timezone (e.g. Asia/Shanghai, America/New_York)',
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
required: ['operation'],
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
async execute(input: Record<string, unknown>): Promise<MCPToolResult> {
|
|
48
|
+
try {
|
|
49
|
+
const op = String(input.operation);
|
|
50
|
+
const tz = input.timezone as string | undefined;
|
|
51
|
+
|
|
52
|
+
switch (op) {
|
|
53
|
+
case 'now': {
|
|
54
|
+
const now = new Date();
|
|
55
|
+
const fmt = (input.format as string) ?? 'iso';
|
|
56
|
+
return { content: formatDate(now, fmt, tz) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
case 'format': {
|
|
60
|
+
const d = parseDate(input.date as string);
|
|
61
|
+
const fmt = (input.format as string) ?? 'iso';
|
|
62
|
+
return { content: formatDate(d, fmt, tz) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
case 'diff': {
|
|
66
|
+
const d1 = parseDate(input.date as string);
|
|
67
|
+
const d2 = input.date2 ? parseDate(input.date2 as string) : new Date();
|
|
68
|
+
const diffMs = d2.getTime() - d1.getTime();
|
|
69
|
+
const days = Math.floor(Math.abs(diffMs) / 86400000);
|
|
70
|
+
const hours = Math.floor((Math.abs(diffMs) % 86400000) / 3600000);
|
|
71
|
+
const mins = Math.floor((Math.abs(diffMs) % 3600000) / 60000);
|
|
72
|
+
const sign = diffMs < 0 ? '-' : '';
|
|
73
|
+
return {
|
|
74
|
+
content: JSON.stringify({
|
|
75
|
+
milliseconds: diffMs,
|
|
76
|
+
readable: `${sign}${days}d ${hours}h ${mins}m`,
|
|
77
|
+
days: diffMs / 86400000,
|
|
78
|
+
}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
case 'add': {
|
|
83
|
+
const d = input.date ? parseDate(input.date as string) : new Date();
|
|
84
|
+
const amount = Number(input.amount ?? 0);
|
|
85
|
+
const unit = String(input.unit ?? 'days');
|
|
86
|
+
const result = addTime(d, amount, unit);
|
|
87
|
+
const fmt = (input.format as string) ?? 'iso';
|
|
88
|
+
return { content: formatDate(result, fmt, tz) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
case 'parse': {
|
|
92
|
+
const d = parseDate(input.date as string);
|
|
93
|
+
return {
|
|
94
|
+
content: JSON.stringify({
|
|
95
|
+
iso: d.toISOString(),
|
|
96
|
+
unix: d.getTime(),
|
|
97
|
+
year: d.getFullYear(),
|
|
98
|
+
month: d.getMonth() + 1,
|
|
99
|
+
day: d.getDate(),
|
|
100
|
+
weekday: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()],
|
|
101
|
+
}),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
default:
|
|
106
|
+
return { content: `Unknown operation: ${op}`, isError: true };
|
|
107
|
+
}
|
|
108
|
+
} catch (err) {
|
|
109
|
+
return { content: `Error: ${(err as Error).message}`, isError: true };
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
function parseDate(s: string): Date {
|
|
115
|
+
const d = new Date(s);
|
|
116
|
+
if (isNaN(d.getTime())) throw new Error(`Invalid date: ${s}`);
|
|
117
|
+
return d;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function formatDate(d: Date, fmt: string, tz?: string): string {
|
|
121
|
+
if (tz) {
|
|
122
|
+
const localeStr = d.toLocaleString('en-US', { timeZone: tz });
|
|
123
|
+
d = new Date(localeStr);
|
|
124
|
+
}
|
|
125
|
+
switch (fmt) {
|
|
126
|
+
case 'iso': return d.toISOString();
|
|
127
|
+
case 'date': return d.toISOString().split('T')[0];
|
|
128
|
+
case 'time': return d.toTimeString().split(' ')[0];
|
|
129
|
+
case 'datetime': return d.toISOString().replace('T', ' ').replace(/\.\d+Z$/, '');
|
|
130
|
+
case 'unix': return String(d.getTime());
|
|
131
|
+
default: return d.toISOString();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function addTime(d: Date, amount: number, unit: string): Date {
|
|
136
|
+
const result = new Date(d);
|
|
137
|
+
switch (unit) {
|
|
138
|
+
case 'milliseconds': result.setTime(result.getTime() + amount); break;
|
|
139
|
+
case 'seconds': result.setTime(result.getTime() + amount * 1000); break;
|
|
140
|
+
case 'minutes': result.setTime(result.getTime() + amount * 60000); break;
|
|
141
|
+
case 'hours': result.setTime(result.getTime() + amount * 3600000); break;
|
|
142
|
+
case 'days': result.setDate(result.getDate() + amount); break;
|
|
143
|
+
case 'weeks': result.setDate(result.getDate() + amount * 7); break;
|
|
144
|
+
case 'months': result.setMonth(result.getMonth() + amount); break;
|
|
145
|
+
case 'years': result.setFullYear(result.getFullYear() + amount); break;
|
|
146
|
+
default: throw new Error(`Unknown unit: ${unit}`);
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { MCPTool, MCPToolResult } from './mcp';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* JSON Transform Tool — v0.8.0
|
|
5
|
+
* Parse, query, and transform JSON data as an LLM function tool.
|
|
6
|
+
*/
|
|
7
|
+
export const JsonTransformTool: MCPTool = {
|
|
8
|
+
name: 'json_transform',
|
|
9
|
+
description: 'Parse, query (JSONPath-like), transform, flatten, or merge JSON data.',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
type: 'object',
|
|
12
|
+
properties: {
|
|
13
|
+
operation: {
|
|
14
|
+
type: 'string',
|
|
15
|
+
enum: ['parse', 'query', 'flatten', 'unflatten', 'merge', 'pick', 'omit', 'sort', 'filter', 'map_keys'],
|
|
16
|
+
description: 'Operation to perform on the JSON data',
|
|
17
|
+
},
|
|
18
|
+
data: {
|
|
19
|
+
description: 'JSON string or object to operate on',
|
|
20
|
+
},
|
|
21
|
+
data2: {
|
|
22
|
+
description: 'Second JSON for merge operation',
|
|
23
|
+
},
|
|
24
|
+
path: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
description: 'Dot-notation path for query (e.g. "users.0.name")',
|
|
27
|
+
},
|
|
28
|
+
keys: {
|
|
29
|
+
type: 'array',
|
|
30
|
+
items: { type: 'string' },
|
|
31
|
+
description: 'Keys for pick/omit operations',
|
|
32
|
+
},
|
|
33
|
+
sortBy: {
|
|
34
|
+
type: 'string',
|
|
35
|
+
description: 'Key to sort array by',
|
|
36
|
+
},
|
|
37
|
+
order: {
|
|
38
|
+
type: 'string',
|
|
39
|
+
enum: ['asc', 'desc'],
|
|
40
|
+
},
|
|
41
|
+
filterKey: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
description: 'Key to filter by',
|
|
44
|
+
},
|
|
45
|
+
filterValue: {
|
|
46
|
+
description: 'Value to match for filter',
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
required: ['operation', 'data'],
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
async execute(input: Record<string, unknown>): Promise<MCPToolResult> {
|
|
53
|
+
try {
|
|
54
|
+
const op = String(input.operation);
|
|
55
|
+
const data = typeof input.data === 'string' ? JSON.parse(input.data) : input.data;
|
|
56
|
+
|
|
57
|
+
switch (op) {
|
|
58
|
+
case 'parse':
|
|
59
|
+
return { content: JSON.stringify(data, null, 2) };
|
|
60
|
+
|
|
61
|
+
case 'query': {
|
|
62
|
+
const path = String(input.path ?? '');
|
|
63
|
+
const result = getByPath(data, path);
|
|
64
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
case 'flatten':
|
|
68
|
+
return { content: JSON.stringify(flatten(data), null, 2) };
|
|
69
|
+
|
|
70
|
+
case 'unflatten':
|
|
71
|
+
return { content: JSON.stringify(unflatten(data as Record<string, unknown>), null, 2) };
|
|
72
|
+
|
|
73
|
+
case 'merge': {
|
|
74
|
+
const data2 = typeof input.data2 === 'string' ? JSON.parse(input.data2) : input.data2;
|
|
75
|
+
return { content: JSON.stringify(deepMerge(data, data2), null, 2) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
case 'pick': {
|
|
79
|
+
const keys = input.keys as string[] ?? [];
|
|
80
|
+
const result: Record<string, unknown> = {};
|
|
81
|
+
for (const k of keys) {
|
|
82
|
+
if (k in data) result[k] = data[k];
|
|
83
|
+
}
|
|
84
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
case 'omit': {
|
|
88
|
+
const keys = new Set(input.keys as string[] ?? []);
|
|
89
|
+
const result: Record<string, unknown> = {};
|
|
90
|
+
for (const [k, v] of Object.entries(data)) {
|
|
91
|
+
if (!keys.has(k)) result[k] = v;
|
|
92
|
+
}
|
|
93
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
case 'sort': {
|
|
97
|
+
if (!Array.isArray(data)) return { content: 'Data must be an array for sort', isError: true };
|
|
98
|
+
const sortBy = String(input.sortBy ?? '');
|
|
99
|
+
const order = input.order === 'desc' ? -1 : 1;
|
|
100
|
+
const sorted = [...data].sort((a, b) => {
|
|
101
|
+
const va = sortBy ? a[sortBy] : a;
|
|
102
|
+
const vb = sortBy ? b[sortBy] : b;
|
|
103
|
+
return va < vb ? -order : va > vb ? order : 0;
|
|
104
|
+
});
|
|
105
|
+
return { content: JSON.stringify(sorted, null, 2) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
case 'filter': {
|
|
109
|
+
if (!Array.isArray(data)) return { content: 'Data must be an array for filter', isError: true };
|
|
110
|
+
const fk = String(input.filterKey ?? '');
|
|
111
|
+
const fv = input.filterValue;
|
|
112
|
+
const filtered = data.filter((item) => item[fk] === fv);
|
|
113
|
+
return { content: JSON.stringify(filtered, null, 2) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
case 'map_keys': {
|
|
117
|
+
// Rename keys: path is "old:new,old2:new2"
|
|
118
|
+
const mapping = String(input.path ?? '').split(',').reduce((acc, pair) => {
|
|
119
|
+
const [old, nw] = pair.split(':');
|
|
120
|
+
if (old && nw) acc[old.trim()] = nw.trim();
|
|
121
|
+
return acc;
|
|
122
|
+
}, {} as Record<string, string>);
|
|
123
|
+
const result: Record<string, unknown> = {};
|
|
124
|
+
for (const [k, v] of Object.entries(data)) {
|
|
125
|
+
result[mapping[k] ?? k] = v;
|
|
126
|
+
}
|
|
127
|
+
return { content: JSON.stringify(result, null, 2) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
default:
|
|
131
|
+
return { content: `Unknown operation: ${op}`, isError: true };
|
|
132
|
+
}
|
|
133
|
+
} catch (err) {
|
|
134
|
+
return { content: `Error: ${(err as Error).message}`, isError: true };
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
function getByPath(obj: unknown, path: string): unknown {
|
|
140
|
+
return path.split('.').reduce((curr: any, key) => {
|
|
141
|
+
if (curr == null) return undefined;
|
|
142
|
+
const idx = Number(key);
|
|
143
|
+
return Number.isInteger(idx) && Array.isArray(curr) ? curr[idx] : curr[key];
|
|
144
|
+
}, obj);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function flatten(obj: unknown, prefix = ''): Record<string, unknown> {
|
|
148
|
+
const result: Record<string, unknown> = {};
|
|
149
|
+
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
150
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
151
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
152
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
|
153
|
+
Object.assign(result, flatten(v, key));
|
|
154
|
+
} else {
|
|
155
|
+
result[key] = v;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function unflatten(obj: Record<string, unknown>): Record<string, unknown> {
|
|
163
|
+
const result: Record<string, unknown> = {};
|
|
164
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
165
|
+
const parts = key.split('.');
|
|
166
|
+
let curr: any = result;
|
|
167
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
168
|
+
if (!(parts[i] in curr)) curr[parts[i]] = {};
|
|
169
|
+
curr = curr[parts[i]];
|
|
170
|
+
}
|
|
171
|
+
curr[parts[parts.length - 1]] = value;
|
|
172
|
+
}
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function deepMerge(a: any, b: any): any {
|
|
177
|
+
if (!b) return a;
|
|
178
|
+
const result = { ...a };
|
|
179
|
+
for (const [k, v] of Object.entries(b)) {
|
|
180
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && result[k] && typeof result[k] === 'object') {
|
|
181
|
+
result[k] = deepMerge(result[k], v);
|
|
182
|
+
} else {
|
|
183
|
+
result[k] = v;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return result;
|
|
187
|
+
}
|