@yumdee/mcp-studio-agent-kit 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +32 -0
- package/dist/__tests__/agent.test.d.ts +2 -0
- package/dist/__tests__/agent.test.d.ts.map +1 -0
- package/dist/__tests__/agent.test.js +27 -0
- package/dist/__tests__/agent.test.js.map +1 -0
- package/dist/__tests__/router.test.d.ts +2 -0
- package/dist/__tests__/router.test.d.ts.map +1 -0
- package/dist/__tests__/router.test.js +163 -0
- package/dist/__tests__/router.test.js.map +1 -0
- package/dist/index.d.ts +82 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +319 -0
- package/dist/index.js.map +1 -0
- package/dist/router.d.ts +91 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +234 -0
- package/dist/router.js.map +1 -0
- package/package.json +37 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# License
|
|
2
|
+
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2024 yumdee-Mcp-studio Contributors
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# @yumdee/mcp-studio-agent-kit
|
|
2
|
+
|
|
3
|
+
Compose 2+ installed MCP servers into a single agent with a unified tool list.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Compose multiple MCP servers into one agent
|
|
8
|
+
- Unified tool list (de-duped, namespaced)
|
|
9
|
+
- Adapters for Anthropic, OpenAI, Ollama
|
|
10
|
+
- Basic agentic loop (plan → call tool → observe → repeat)
|
|
11
|
+
- Auto-record all steps to core's session format
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { ComposedAgent } from "@yumdee/mcp-studio-agent-kit";
|
|
17
|
+
import { createStdioClient } from "@yumdee/mcp-studio-core";
|
|
18
|
+
|
|
19
|
+
const postgres = createStdioClient("npx postgres-mcp");
|
|
20
|
+
const filesystem = createStdioClient("npx filesystem-mcp");
|
|
21
|
+
|
|
22
|
+
const agent = new ComposedAgent([postgres, filesystem], {
|
|
23
|
+
model: "gpt-4",
|
|
24
|
+
maxSteps: 10,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const result = await agent.run("Query my database and save results to file");
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Development
|
|
31
|
+
|
|
32
|
+
See [../../CONTRIBUTING.md](../../CONTRIBUTING.md)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/agent.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { describe, it, expect, afterAll } from "vitest";
|
|
2
|
+
import { createAgent } from "../index.js";
|
|
3
|
+
import { createStdioClient } from "@yumdee/mcp-studio-core";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
describe("Agent-Kit Multi-Server Orchestrator", () => {
|
|
6
|
+
let client;
|
|
7
|
+
const serverPath = path.resolve(__dirname, "../../../../examples/math-server/dist/index.js");
|
|
8
|
+
afterAll(async () => {
|
|
9
|
+
if (client) {
|
|
10
|
+
await client.disconnect();
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
it("should aggregate tools across servers and run an agent loop", async () => {
|
|
14
|
+
client = createStdioClient("node", [serverPath]);
|
|
15
|
+
const agent = createAgent({
|
|
16
|
+
servers: [client],
|
|
17
|
+
model: "mock",
|
|
18
|
+
});
|
|
19
|
+
const answer = await agent.run("Please add two numbers together");
|
|
20
|
+
expect(answer).toContain("42");
|
|
21
|
+
const session = agent.getSession();
|
|
22
|
+
expect(session).toBeDefined();
|
|
23
|
+
expect(session?.metadata?.tags).toContain("agent-run");
|
|
24
|
+
expect(session?.events.length).toBeGreaterThan(0);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
//# sourceMappingURL=agent.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.test.js","sourceRoot":"","sources":["../../src/__tests__/agent.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACxD,OAAO,EAAE,WAAW,EAAS,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAa,MAAM,yBAAyB,CAAC;AACvE,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,QAAQ,CAAC,qCAAqC,EAAE,GAAG,EAAE;IACnD,IAAI,MAAiB,CAAC;IACtB,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,gDAAgD,CAAC,CAAC;IAE7F,QAAQ,CAAC,KAAK,IAAI,EAAE;QAClB,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,MAAM,CAAC,UAAU,EAAE,CAAC;QAC5B,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;QAC3E,MAAM,GAAG,iBAAiB,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;QACjD,MAAM,KAAK,GAAG,WAAW,CAAC;YACxB,OAAO,EAAE,CAAC,MAAM,CAAC;YACjB,KAAK,EAAE,MAAM;SACd,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;QAClE,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;QAE/B,MAAM,OAAO,GAAG,KAAK,CAAC,UAAU,EAAE,CAAC;QACnC,MAAM,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9B,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACvD,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/router.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { SemanticToolRouter, SparseSemanticVectorizer, cosineSimilarity, createAgent, } from "../index.js";
|
|
3
|
+
describe("Vector Similarity & Tokenizer", () => {
|
|
4
|
+
it("computes cosine similarity accurately", () => {
|
|
5
|
+
expect(cosineSimilarity([1, 0, 0], [0, 1, 0])).toBe(0);
|
|
6
|
+
expect(cosineSimilarity([1, 1], [1, 1])).toBeCloseTo(1, 5);
|
|
7
|
+
expect(cosineSimilarity([2, 0], [10, 0])).toBeCloseTo(1, 5);
|
|
8
|
+
expect(cosineSimilarity([], [])).toBe(0);
|
|
9
|
+
});
|
|
10
|
+
it("tokenizes camelCase, snake_case, and subword n-grams", () => {
|
|
11
|
+
const vectorizer = new SparseSemanticVectorizer();
|
|
12
|
+
const tokens = vectorizer.tokenize("calculateTax_rate in postgresDB");
|
|
13
|
+
expect(tokens).toContain("calculate");
|
|
14
|
+
expect(tokens).toContain("tax");
|
|
15
|
+
expect(tokens).toContain("rate");
|
|
16
|
+
expect(tokens).toContain("postgres");
|
|
17
|
+
expect(tokens).toContain("db");
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
describe("SemanticToolRouter", () => {
|
|
21
|
+
const tools = [
|
|
22
|
+
{
|
|
23
|
+
name: "calculate",
|
|
24
|
+
description: "Perform mathematical calculations like addition, multiplication, division, and subtraction.",
|
|
25
|
+
inputSchema: {
|
|
26
|
+
type: "object",
|
|
27
|
+
properties: {
|
|
28
|
+
operation: { type: "string", description: "The arithmetic operation: add, subtract, multiply, divide" },
|
|
29
|
+
a: { type: "number", description: "First operand" },
|
|
30
|
+
b: { type: "number", description: "Second operand" },
|
|
31
|
+
},
|
|
32
|
+
required: ["operation", "a", "b"],
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "read_file",
|
|
37
|
+
description: "Read contents of a text or markdown file from the local filesystem.",
|
|
38
|
+
inputSchema: {
|
|
39
|
+
type: "object",
|
|
40
|
+
properties: {
|
|
41
|
+
filepath: { type: "string", description: "Absolute path to the target file on disk" },
|
|
42
|
+
},
|
|
43
|
+
required: ["filepath"],
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: "send_slack_message",
|
|
48
|
+
description: "Post a chat notification message or alert to a team Slack channel.",
|
|
49
|
+
inputSchema: {
|
|
50
|
+
type: "object",
|
|
51
|
+
properties: {
|
|
52
|
+
channel: { type: "string", description: "Slack channel ID or name" },
|
|
53
|
+
message: { type: "string", description: "Text message to send" },
|
|
54
|
+
},
|
|
55
|
+
required: ["channel", "message"],
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: "execute_sql_query",
|
|
60
|
+
description: "Run SQL SELECT or UPDATE queries against the production PostgreSQL database.",
|
|
61
|
+
inputSchema: {
|
|
62
|
+
type: "object",
|
|
63
|
+
properties: {
|
|
64
|
+
query: { type: "string", description: "SQL query string to execute" },
|
|
65
|
+
timeoutMs: { type: "number", description: "Query timeout in milliseconds" },
|
|
66
|
+
},
|
|
67
|
+
required: ["query"],
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
];
|
|
71
|
+
it("routes math queries to calculate tool and prunes unrelated tools", async () => {
|
|
72
|
+
const router = new SemanticToolRouter({ topK: 1, minScore: 0.05 });
|
|
73
|
+
await router.indexTools(tools);
|
|
74
|
+
const result = await router.route("What is 45 multiplied by 8?");
|
|
75
|
+
expect(result.selectedTools.length).toBe(1);
|
|
76
|
+
expect(result.selectedTools[0].name).toBe("calculate");
|
|
77
|
+
expect(result.metrics.totalTools).toBe(4);
|
|
78
|
+
expect(result.metrics.selectedCount).toBe(1);
|
|
79
|
+
expect(result.metrics.prunedCount).toBe(3);
|
|
80
|
+
expect(result.metrics.reductionPercentage).toBeGreaterThanOrEqual(70);
|
|
81
|
+
expect(result.metrics.tokensSaved).toBeGreaterThan(0);
|
|
82
|
+
});
|
|
83
|
+
it("routes database queries to execute_sql_query", async () => {
|
|
84
|
+
const router = new SemanticToolRouter({ topK: 2, minScore: 0.05 });
|
|
85
|
+
await router.indexTools(tools);
|
|
86
|
+
const result = await router.route("Run a SELECT count(*) from customer orders in postgres");
|
|
87
|
+
expect(result.selectedTools.length).toBeGreaterThanOrEqual(1);
|
|
88
|
+
expect(result.selectedTools[0].name).toBe("execute_sql_query");
|
|
89
|
+
});
|
|
90
|
+
it("routes file operations to read_file", async () => {
|
|
91
|
+
const router = new SemanticToolRouter({ topK: 1, minScore: 0.05 });
|
|
92
|
+
await router.indexTools(tools);
|
|
93
|
+
const result = await router.route("Open and read the file from disk");
|
|
94
|
+
expect(result.selectedTools[0].name).toBe("read_file");
|
|
95
|
+
});
|
|
96
|
+
it("supports custom embedding providers", async () => {
|
|
97
|
+
// Mock dense embedding function
|
|
98
|
+
const mockEmbedFn = async (text) => {
|
|
99
|
+
const isMath = text.includes("math") || text.includes("calculate") || text.includes("add");
|
|
100
|
+
return isMath ? [1, 0, 0] : [0, 1, 0];
|
|
101
|
+
};
|
|
102
|
+
const router = new SemanticToolRouter({
|
|
103
|
+
topK: 1,
|
|
104
|
+
minScore: 0.5,
|
|
105
|
+
embedFn: mockEmbedFn,
|
|
106
|
+
});
|
|
107
|
+
await router.indexTools(tools);
|
|
108
|
+
const result = await router.route("calculate 20 plus 30");
|
|
109
|
+
expect(result.selectedTools[0].name).toBe("calculate");
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
describe("Agent with Semantic Routing", () => {
|
|
113
|
+
it("runs with semantic routing enabled and tracks token savings metrics", async () => {
|
|
114
|
+
const mockClient = {
|
|
115
|
+
connect: async () => ({ name: "math-server", version: "1.0.0", transport: "stdio" }),
|
|
116
|
+
disconnect: async () => { },
|
|
117
|
+
isConnected: () => true,
|
|
118
|
+
call: async () => ({ content: [{ type: "text", text: "42" }] }),
|
|
119
|
+
notify: async () => { },
|
|
120
|
+
onNotification: () => () => { },
|
|
121
|
+
getCapabilities: () => ({}),
|
|
122
|
+
getSession: () => ({
|
|
123
|
+
id: "mock-session",
|
|
124
|
+
serverInfo: { name: "math-server", version: "1.0.0", transport: "stdio" },
|
|
125
|
+
clientInfo: { name: "yumdee-mcp-studio", version: "0.1.0" },
|
|
126
|
+
startedAt: new Date().toISOString(),
|
|
127
|
+
events: [],
|
|
128
|
+
}),
|
|
129
|
+
clearSession: () => { },
|
|
130
|
+
getServerInfo: () => ({ name: "math-server", version: "1.0.0", transport: "stdio" }),
|
|
131
|
+
getTools: () => [
|
|
132
|
+
{
|
|
133
|
+
name: "add",
|
|
134
|
+
description: "Add two numbers together",
|
|
135
|
+
inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } } },
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: "delete_database",
|
|
139
|
+
description: "Drop all tables in database",
|
|
140
|
+
inputSchema: { type: "object", properties: {} },
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
getResources: () => [],
|
|
144
|
+
getPrompts: () => [],
|
|
145
|
+
getEvents: () => [],
|
|
146
|
+
};
|
|
147
|
+
const agent = createAgent({
|
|
148
|
+
servers: [mockClient],
|
|
149
|
+
model: "mock",
|
|
150
|
+
useSemanticRouting: true,
|
|
151
|
+
semanticRouterConfig: { topK: 1 },
|
|
152
|
+
});
|
|
153
|
+
const result = await agent.run("Please add two numbers");
|
|
154
|
+
expect(result).toBe("The calculation was completed successfully. The answer is 42.");
|
|
155
|
+
const metrics = agent.getRoutingMetrics();
|
|
156
|
+
expect(metrics).toBeDefined();
|
|
157
|
+
expect(metrics?.totalTools).toBe(2);
|
|
158
|
+
expect(metrics?.selectedCount).toBe(1);
|
|
159
|
+
expect(metrics?.prunedCount).toBe(1);
|
|
160
|
+
expect(metrics?.reductionPercentage).toBe(50);
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
//# sourceMappingURL=router.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.test.js","sourceRoot":"","sources":["../../src/__tests__/router.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EACL,kBAAkB,EAClB,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AAE,CAAC,EAAE;SAClC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QACzD,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,+DAA+D,CAAC,CAAC;QAErF,MAAM,OAAO,GAAG,KAAK,CAAC,iBAAiB,EAAE,CAAC;QAC1C,MAAM,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9B,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvC,MAAM,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACrC,MAAM,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAChD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yumdee/mcp-studio-agent-kit
|
|
3
|
+
*
|
|
4
|
+
* Orchestration layer for composing multiple MCP servers into a unified agent.
|
|
5
|
+
*
|
|
6
|
+
* Supports chaining multiple MCP servers with different reasoning models:
|
|
7
|
+
* - Local Ollama models (free, local, no API keys needed)
|
|
8
|
+
* - OpenAI GPT
|
|
9
|
+
* - Anthropic Claude
|
|
10
|
+
* - Deterministic/Mock agent for testing & offline workflows
|
|
11
|
+
*/
|
|
12
|
+
import { McpClient, McpSession, ToolDefinition } from "@yumdee/mcp-studio-core";
|
|
13
|
+
import { SemanticToolRouter, type SemanticRouterConfig, type RouteResult, SparseSemanticVectorizer, cosineSimilarity } from "./router.js";
|
|
14
|
+
export { SemanticToolRouter, type SemanticRouterConfig, type RouteResult, SparseSemanticVectorizer, cosineSimilarity, };
|
|
15
|
+
/**
|
|
16
|
+
* Agent configuration
|
|
17
|
+
*/
|
|
18
|
+
export interface AgentConfig {
|
|
19
|
+
servers: McpClient[];
|
|
20
|
+
model: "claude" | "gpt" | "ollama" | "mock";
|
|
21
|
+
modelName?: string;
|
|
22
|
+
apiKey?: string;
|
|
23
|
+
baseUrl?: string;
|
|
24
|
+
maxSteps?: number;
|
|
25
|
+
systemPrompt?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Enable dynamic semantic tool routing using vector embeddings
|
|
28
|
+
* Prunes unused tools from prompts, drastically reducing tokens and preventing hallucination.
|
|
29
|
+
*/
|
|
30
|
+
useSemanticRouting?: boolean;
|
|
31
|
+
semanticRouterConfig?: SemanticRouterConfig;
|
|
32
|
+
}
|
|
33
|
+
interface DiscoveredTool {
|
|
34
|
+
client: McpClient;
|
|
35
|
+
originalName: string;
|
|
36
|
+
uniqueName: string;
|
|
37
|
+
definition: ToolDefinition;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Agent orchestrator
|
|
41
|
+
*/
|
|
42
|
+
export declare class Agent {
|
|
43
|
+
private servers;
|
|
44
|
+
private model;
|
|
45
|
+
private modelName;
|
|
46
|
+
private apiKey?;
|
|
47
|
+
private baseUrl?;
|
|
48
|
+
private maxSteps;
|
|
49
|
+
private systemPrompt?;
|
|
50
|
+
private useSemanticRouting;
|
|
51
|
+
private router?;
|
|
52
|
+
private lastRoutingMetrics?;
|
|
53
|
+
private toolsMap;
|
|
54
|
+
private session?;
|
|
55
|
+
constructor(config: AgentConfig);
|
|
56
|
+
/**
|
|
57
|
+
* Introspect and aggregate tools across all connected MCP servers
|
|
58
|
+
*/
|
|
59
|
+
discoverTools(): Promise<Map<string, DiscoveredTool>>;
|
|
60
|
+
/**
|
|
61
|
+
* Run the agent to achieve a goal
|
|
62
|
+
*/
|
|
63
|
+
run(goal: string): Promise<string>;
|
|
64
|
+
/**
|
|
65
|
+
* Internal model dispatch
|
|
66
|
+
*/
|
|
67
|
+
private callModel;
|
|
68
|
+
/**
|
|
69
|
+
* Get the session recording for this agent run
|
|
70
|
+
*/
|
|
71
|
+
getSession(): McpSession | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Get metrics from the latest semantic routing step
|
|
74
|
+
*/
|
|
75
|
+
getRoutingMetrics(): RouteResult["metrics"] | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Get the underlying SemanticToolRouter instance
|
|
78
|
+
*/
|
|
79
|
+
getRouter(): SemanticToolRouter | undefined;
|
|
80
|
+
}
|
|
81
|
+
export declare function createAgent(config: AgentConfig): Agent;
|
|
82
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAY,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC1F,OAAO,EACL,kBAAkB,EAClB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,wBAAwB,EACxB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,kBAAkB,EAClB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,wBAAwB,EACxB,gBAAgB,GACjB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,SAAS,EAAE,CAAC;IACrB,KAAK,EAAE,QAAQ,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,oBAAoB,CAAC,EAAE,oBAA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+
*
|
|
6
|
+
* Supports chaining multiple MCP servers with different reasoning models:
|
|
7
|
+
* - Local Ollama models (free, local, no API keys needed)
|
|
8
|
+
* - OpenAI GPT
|
|
9
|
+
* - Anthropic Claude
|
|
10
|
+
* - Deterministic/Mock agent for testing & offline workflows
|
|
11
|
+
*/
|
|
12
|
+
import { randomUUID } from "crypto";
|
|
13
|
+
import { SemanticToolRouter, SparseSemanticVectorizer, cosineSimilarity, } from "./router.js";
|
|
14
|
+
export { SemanticToolRouter, SparseSemanticVectorizer, cosineSimilarity, };
|
|
15
|
+
/**
|
|
16
|
+
* Agent orchestrator
|
|
17
|
+
*/
|
|
18
|
+
export class Agent {
|
|
19
|
+
constructor(config) {
|
|
20
|
+
this.toolsMap = new Map();
|
|
21
|
+
this.servers = config.servers;
|
|
22
|
+
this.model = config.model;
|
|
23
|
+
this.modelName = config.modelName || (config.model === "ollama" ? "llama3" : config.model === "claude" ? "claude-3-5-sonnet-20241022" : "gpt-4o");
|
|
24
|
+
this.apiKey = config.apiKey || (config.model === "claude" ? process.env.ANTHROPIC_API_KEY : process.env.OPENAI_API_KEY);
|
|
25
|
+
this.baseUrl = config.baseUrl;
|
|
26
|
+
this.maxSteps = config.maxSteps || 10;
|
|
27
|
+
this.systemPrompt = config.systemPrompt;
|
|
28
|
+
this.useSemanticRouting = config.useSemanticRouting ?? false;
|
|
29
|
+
if (this.useSemanticRouting) {
|
|
30
|
+
this.router = new SemanticToolRouter(config.semanticRouterConfig);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Introspect and aggregate tools across all connected MCP servers
|
|
35
|
+
*/
|
|
36
|
+
async discoverTools() {
|
|
37
|
+
this.toolsMap.clear();
|
|
38
|
+
for (const client of this.servers) {
|
|
39
|
+
if (!client.isConnected()) {
|
|
40
|
+
await client.connect();
|
|
41
|
+
}
|
|
42
|
+
const sInfo = client.getServerInfo();
|
|
43
|
+
const clientTools = client.getTools();
|
|
44
|
+
for (const tool of clientTools) {
|
|
45
|
+
let uniqueName = tool.name;
|
|
46
|
+
if (this.toolsMap.has(uniqueName)) {
|
|
47
|
+
uniqueName = `${sInfo.name}__${tool.name}`;
|
|
48
|
+
}
|
|
49
|
+
this.toolsMap.set(uniqueName, {
|
|
50
|
+
client,
|
|
51
|
+
originalName: tool.name,
|
|
52
|
+
uniqueName,
|
|
53
|
+
definition: {
|
|
54
|
+
...tool,
|
|
55
|
+
name: uniqueName,
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return this.toolsMap;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Run the agent to achieve a goal
|
|
64
|
+
*/
|
|
65
|
+
async run(goal) {
|
|
66
|
+
await this.discoverTools();
|
|
67
|
+
if (this.useSemanticRouting && this.router) {
|
|
68
|
+
const toolDefs = Array.from(this.toolsMap.values()).map((t) => t.definition);
|
|
69
|
+
await this.router.indexTools(toolDefs);
|
|
70
|
+
}
|
|
71
|
+
const sessionId = randomUUID();
|
|
72
|
+
const startedAt = new Date().toISOString();
|
|
73
|
+
const messages = [
|
|
74
|
+
{
|
|
75
|
+
role: "system",
|
|
76
|
+
content: this.systemPrompt ||
|
|
77
|
+
`You are an autonomous AI agent equipped with tools from multiple Model Context Protocol (MCP) servers. Your objective is to achieve the user's goal by selecting the right tools, analyzing results, and providing a final answer. Available tools: ${Array.from(this.toolsMap.keys()).join(", ")}.`,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
role: "user",
|
|
81
|
+
content: goal,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
let currentStep = 0;
|
|
85
|
+
let finalAnswer = "";
|
|
86
|
+
while (currentStep < this.maxSteps) {
|
|
87
|
+
currentStep++;
|
|
88
|
+
// Dynamically select tools using semantic routing if enabled
|
|
89
|
+
let activeTools = Array.from(this.toolsMap.values());
|
|
90
|
+
if (this.useSemanticRouting && this.router) {
|
|
91
|
+
const lastMsg = messages[messages.length - 1]?.content;
|
|
92
|
+
const query = typeof lastMsg === "string" ? `${goal} ${lastMsg}` : goal;
|
|
93
|
+
const routeResult = await this.router.route(query);
|
|
94
|
+
this.lastRoutingMetrics = routeResult.metrics;
|
|
95
|
+
const selectedNames = new Set(routeResult.selectedTools.map((t) => t.name));
|
|
96
|
+
activeTools = activeTools.filter((t) => selectedNames.has(t.uniqueName) || selectedNames.has(t.originalName));
|
|
97
|
+
}
|
|
98
|
+
// Dispatch to model adapter with dynamically routed tools
|
|
99
|
+
const stepResponse = await this.callModel(messages, activeTools);
|
|
100
|
+
if (stepResponse.toolCalls && stepResponse.toolCalls.length > 0) {
|
|
101
|
+
messages.push({
|
|
102
|
+
role: "assistant",
|
|
103
|
+
content: stepResponse.content || null,
|
|
104
|
+
});
|
|
105
|
+
for (const tc of stepResponse.toolCalls) {
|
|
106
|
+
const toolHandler = this.toolsMap.get(tc.name);
|
|
107
|
+
if (!toolHandler) {
|
|
108
|
+
messages.push({
|
|
109
|
+
role: "user",
|
|
110
|
+
content: `Error: Tool "${tc.name}" is not registered. Available tools: ${Array.from(this.toolsMap.keys()).join(", ")}`,
|
|
111
|
+
});
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const toolResult = await toolHandler.client.call("tools/call", {
|
|
116
|
+
name: toolHandler.originalName,
|
|
117
|
+
arguments: tc.args || {},
|
|
118
|
+
});
|
|
119
|
+
messages.push({
|
|
120
|
+
role: "user",
|
|
121
|
+
content: `Tool Result for ${tc.name}:\n${JSON.stringify(toolResult, null, 2)}`,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
messages.push({
|
|
126
|
+
role: "user",
|
|
127
|
+
content: `Tool Execution Error for ${tc.name}: ${err.message}`,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
finalAnswer = stepResponse.content || "Goal completed.";
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (!finalAnswer && currentStep >= this.maxSteps) {
|
|
138
|
+
finalAnswer = `Max execution steps (${this.maxSteps}) reached. Last state: ${JSON.stringify(messages[messages.length - 1].content)}`;
|
|
139
|
+
}
|
|
140
|
+
// Collate all events into a unified McpSession
|
|
141
|
+
const allEvents = [];
|
|
142
|
+
for (const client of this.servers) {
|
|
143
|
+
allEvents.push(...client.getEvents());
|
|
144
|
+
}
|
|
145
|
+
allEvents.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
|
|
146
|
+
this.session = {
|
|
147
|
+
id: sessionId,
|
|
148
|
+
serverInfo: {
|
|
149
|
+
name: `orchestrated-agent [${this.servers.map((s) => s.getServerInfo().name).join(", ")}]`,
|
|
150
|
+
version: "0.1.0",
|
|
151
|
+
transport: "stdio",
|
|
152
|
+
},
|
|
153
|
+
clientInfo: {
|
|
154
|
+
name: "yumdee-mcp-studio",
|
|
155
|
+
version: "0.1.0",
|
|
156
|
+
},
|
|
157
|
+
startedAt,
|
|
158
|
+
endedAt: new Date().toISOString(),
|
|
159
|
+
events: allEvents,
|
|
160
|
+
metadata: {
|
|
161
|
+
tags: ["agent-run", this.model, ...(this.useSemanticRouting ? ["semantic-routing"] : [])],
|
|
162
|
+
notes: `Goal: ${goal} | Steps: ${currentStep}`,
|
|
163
|
+
routingMetrics: this.lastRoutingMetrics,
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
return finalAnswer;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Internal model dispatch
|
|
170
|
+
*/
|
|
171
|
+
async callModel(messages, activeTools) {
|
|
172
|
+
const toolsPool = activeTools && activeTools.length > 0 ? activeTools : Array.from(this.toolsMap.values());
|
|
173
|
+
if (this.model === "mock") {
|
|
174
|
+
// Deterministic mock agent for tests and headless verification
|
|
175
|
+
const lastMsg = messages[messages.length - 1].content;
|
|
176
|
+
if (typeof lastMsg === "string" && lastMsg.toLowerCase().includes("add")) {
|
|
177
|
+
const hasExecuted = messages.some((m) => typeof m.content === "string" && m.content.includes("Tool Result"));
|
|
178
|
+
if (!hasExecuted) {
|
|
179
|
+
return {
|
|
180
|
+
toolCalls: [{ name: "add", args: { a: 20, b: 22 } }],
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
return {
|
|
185
|
+
content: "The calculation was completed successfully. The answer is 42.",
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return { content: "Mock goal processed." };
|
|
190
|
+
}
|
|
191
|
+
if (this.model === "ollama") {
|
|
192
|
+
const host = this.baseUrl || process.env.OLLAMA_HOST || "http://localhost:11434";
|
|
193
|
+
const tools = toolsPool.map((t) => ({
|
|
194
|
+
type: "function",
|
|
195
|
+
function: {
|
|
196
|
+
name: t.uniqueName,
|
|
197
|
+
description: t.definition.description || "",
|
|
198
|
+
parameters: t.definition.inputSchema || { type: "object", properties: {} },
|
|
199
|
+
},
|
|
200
|
+
}));
|
|
201
|
+
const res = await fetch(`${host}/api/chat`, {
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers: { "Content-Type": "application/json" },
|
|
204
|
+
body: JSON.stringify({
|
|
205
|
+
model: this.modelName,
|
|
206
|
+
messages,
|
|
207
|
+
tools,
|
|
208
|
+
stream: false,
|
|
209
|
+
}),
|
|
210
|
+
});
|
|
211
|
+
if (!res.ok)
|
|
212
|
+
throw new Error(`Ollama request failed: ${res.statusText}`);
|
|
213
|
+
const data = await res.json();
|
|
214
|
+
const msg = data.message || {};
|
|
215
|
+
const toolCalls = msg.tool_calls?.map((tc) => ({
|
|
216
|
+
name: tc.function?.name,
|
|
217
|
+
args: tc.function?.arguments,
|
|
218
|
+
}));
|
|
219
|
+
return { content: msg.content, toolCalls };
|
|
220
|
+
}
|
|
221
|
+
if (this.model === "gpt") {
|
|
222
|
+
if (!this.apiKey) {
|
|
223
|
+
throw new Error("OPENAI_API_KEY is required for GPT model adapter");
|
|
224
|
+
}
|
|
225
|
+
const tools = toolsPool.map((t) => ({
|
|
226
|
+
type: "function",
|
|
227
|
+
function: {
|
|
228
|
+
name: t.uniqueName,
|
|
229
|
+
description: t.definition.description || "",
|
|
230
|
+
parameters: t.definition.inputSchema || { type: "object", properties: {} },
|
|
231
|
+
},
|
|
232
|
+
}));
|
|
233
|
+
const res = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
234
|
+
method: "POST",
|
|
235
|
+
headers: {
|
|
236
|
+
"Content-Type": "application/json",
|
|
237
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
238
|
+
},
|
|
239
|
+
body: JSON.stringify({
|
|
240
|
+
model: this.modelName,
|
|
241
|
+
messages,
|
|
242
|
+
tools: tools.length > 0 ? tools : undefined,
|
|
243
|
+
}),
|
|
244
|
+
});
|
|
245
|
+
if (!res.ok)
|
|
246
|
+
throw new Error(`OpenAI API error: ${res.statusText}`);
|
|
247
|
+
const data = await res.json();
|
|
248
|
+
const choice = data.choices?.[0]?.message;
|
|
249
|
+
const toolCalls = choice?.tool_calls?.map((tc) => ({
|
|
250
|
+
name: tc.function?.name,
|
|
251
|
+
args: JSON.parse(tc.function?.arguments || "{}"),
|
|
252
|
+
}));
|
|
253
|
+
return { content: choice?.content, toolCalls };
|
|
254
|
+
}
|
|
255
|
+
if (this.model === "claude") {
|
|
256
|
+
if (!this.apiKey) {
|
|
257
|
+
throw new Error("ANTHROPIC_API_KEY is required for Claude model adapter");
|
|
258
|
+
}
|
|
259
|
+
const tools = toolsPool.map((t) => ({
|
|
260
|
+
name: t.uniqueName,
|
|
261
|
+
description: t.definition.description || "",
|
|
262
|
+
input_schema: t.definition.inputSchema || { type: "object", properties: {} },
|
|
263
|
+
}));
|
|
264
|
+
// Extract system message for Anthropic format
|
|
265
|
+
const system = messages.find((m) => m.role === "system")?.content;
|
|
266
|
+
const conversation = messages
|
|
267
|
+
.filter((m) => m.role !== "system")
|
|
268
|
+
.map((m) => ({ role: m.role === "assistant" ? "assistant" : "user", content: m.content }));
|
|
269
|
+
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
270
|
+
method: "POST",
|
|
271
|
+
headers: {
|
|
272
|
+
"Content-Type": "application/json",
|
|
273
|
+
"x-api-key": this.apiKey,
|
|
274
|
+
"anthropic-version": "2023-06-01",
|
|
275
|
+
},
|
|
276
|
+
body: JSON.stringify({
|
|
277
|
+
model: this.modelName,
|
|
278
|
+
max_tokens: 1024,
|
|
279
|
+
system,
|
|
280
|
+
messages: conversation,
|
|
281
|
+
tools: tools.length > 0 ? tools : undefined,
|
|
282
|
+
}),
|
|
283
|
+
});
|
|
284
|
+
if (!res.ok)
|
|
285
|
+
throw new Error(`Anthropic API error: ${res.statusText}`);
|
|
286
|
+
const data = await res.json();
|
|
287
|
+
const toolUseBlocks = data.content?.filter((c) => c.type === "tool_use");
|
|
288
|
+
const textBlocks = data.content?.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
289
|
+
const toolCalls = toolUseBlocks?.map((tb) => ({
|
|
290
|
+
name: tb.name,
|
|
291
|
+
args: tb.input,
|
|
292
|
+
}));
|
|
293
|
+
return { content: textBlocks, toolCalls };
|
|
294
|
+
}
|
|
295
|
+
return { content: "Unsupported model" };
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Get the session recording for this agent run
|
|
299
|
+
*/
|
|
300
|
+
getSession() {
|
|
301
|
+
return this.session;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Get metrics from the latest semantic routing step
|
|
305
|
+
*/
|
|
306
|
+
getRoutingMetrics() {
|
|
307
|
+
return this.lastRoutingMetrics;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Get the underlying SemanticToolRouter instance
|
|
311
|
+
*/
|
|
312
|
+
getRouter() {
|
|
313
|
+
return this.router;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
export function createAgent(config) {
|
|
317
|
+
return new Agent(config);
|
|
318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;;OAEG;IACH,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAED,MAAM,UAAU,WAAW,CAAC,MAAmB;IAC7C,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC"}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yumdee/mcp-studio-agent-kit - Semantic Tool Router
|
|
3
|
+
*
|
|
4
|
+
* Dynamic tool retrieval & context pruning using vector embeddings and cosine similarity.
|
|
5
|
+
* Drastically reduces context window bloat and eliminates tool hallucination
|
|
6
|
+
* in multi-server MCP environments with 50+ tools.
|
|
7
|
+
*/
|
|
8
|
+
import { ToolDefinition } from "@yumdee/mcp-studio-core";
|
|
9
|
+
export interface SemanticRouterConfig {
|
|
10
|
+
/** Maximum number of tools to select for any given turn (default: 3) */
|
|
11
|
+
topK?: number;
|
|
12
|
+
/** Minimum similarity score threshold between 0 and 1 (default: 0.1) */
|
|
13
|
+
minScore?: number;
|
|
14
|
+
/** Optional custom embedding function (e.g. OpenAI text-embedding-3-small, Ollama nomic-embed-text) */
|
|
15
|
+
embedFn?: (text: string) => Promise<number[]>;
|
|
16
|
+
}
|
|
17
|
+
export interface RouteResult<T = ToolDefinition> {
|
|
18
|
+
selectedTools: T[];
|
|
19
|
+
scores: Array<{
|
|
20
|
+
toolName: string;
|
|
21
|
+
score: number;
|
|
22
|
+
}>;
|
|
23
|
+
metrics: {
|
|
24
|
+
totalTools: number;
|
|
25
|
+
selectedCount: number;
|
|
26
|
+
prunedCount: number;
|
|
27
|
+
estimatedTokensBefore: number;
|
|
28
|
+
estimatedTokensAfter: number;
|
|
29
|
+
tokensSaved: number;
|
|
30
|
+
reductionPercentage: number;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Fast cosine similarity between two dense vectors
|
|
35
|
+
*/
|
|
36
|
+
export declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
37
|
+
/**
|
|
38
|
+
* Built-in Sub-word & N-Gram Sparse Vectorizer
|
|
39
|
+
* High-speed, zero-dependency semantic vectorizer robust to typos,
|
|
40
|
+
* snake_case/camelCase function identifiers, and terminology variations.
|
|
41
|
+
*/
|
|
42
|
+
export declare class SparseSemanticVectorizer {
|
|
43
|
+
private vocabulary;
|
|
44
|
+
private docFrequencies;
|
|
45
|
+
private docCount;
|
|
46
|
+
/**
|
|
47
|
+
* Tokenize and normalize text into word stems and character 3-grams
|
|
48
|
+
*/
|
|
49
|
+
tokenize(text: string): string[];
|
|
50
|
+
/**
|
|
51
|
+
* Build TF-IDF vocabulary across all documents
|
|
52
|
+
*/
|
|
53
|
+
fit(documents: string[]): void;
|
|
54
|
+
/**
|
|
55
|
+
* Transform text into a normalized TF-IDF vector
|
|
56
|
+
*/
|
|
57
|
+
transform(text: string): number[];
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Semantic Tool Router
|
|
61
|
+
*/
|
|
62
|
+
export declare class SemanticToolRouter<T extends {
|
|
63
|
+
name: string;
|
|
64
|
+
description?: string;
|
|
65
|
+
inputSchema?: any;
|
|
66
|
+
} = ToolDefinition> {
|
|
67
|
+
private config;
|
|
68
|
+
private vectorizer;
|
|
69
|
+
private indexedTools;
|
|
70
|
+
constructor(config?: SemanticRouterConfig);
|
|
71
|
+
/**
|
|
72
|
+
* Convert a tool definition into rich textual signature for vectorization
|
|
73
|
+
*/
|
|
74
|
+
static extractToolSignature(tool: {
|
|
75
|
+
name: string;
|
|
76
|
+
description?: string;
|
|
77
|
+
inputSchema?: any;
|
|
78
|
+
}): string;
|
|
79
|
+
/**
|
|
80
|
+
* Index all tools and build vector space representations
|
|
81
|
+
*/
|
|
82
|
+
indexTools(tools: T[]): Promise<void>;
|
|
83
|
+
/**
|
|
84
|
+
* Semantically route a user query to the top-K relevant tools
|
|
85
|
+
*/
|
|
86
|
+
route(query: string, options?: {
|
|
87
|
+
topK?: number;
|
|
88
|
+
minScore?: number;
|
|
89
|
+
}): Promise<RouteResult<T>>;
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uGAAuG;IACvG,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CAC/C;AAED,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,cAAc;IAC7C,aAAa,EAAE,CAAC,EAAE,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACnD,OAAO,EAAE;QACP,UAAU,EAAE,MAAM,CAAC;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,WAAW,EAAE,MAAM,CAAC;QACpB,qBAAqB,EAAE,MAAM,CAAC;QAC9B,oBAAoB,EAAE,MAAM,CAAC;QAC7B,WAAW,EAAE,MAAM,CAAC;QACpB,mBAAmB,EAAE,MAAM,CAAC;KAC7B,CAAC;CACH;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAED;;;;GAIG;AACH,qBAAa,wBAAwB;IACnC,OAAO,CAAC,UAAU,CAAkC;IACpD,OAAO,CAAC,cAAc,CAAkC;IACxD,OAAO,CAAC,QAAQ,CAAa;IAE7B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE;IAsBhC;;OAEG;IACH,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI;IAiB9B;;OAEG;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE;CAiClC;AAED;;GAEG;AACH,qBAAa,kBAAkB,CAAC,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,GAAG,CAAA;CAAE,GAAG,cAAc;IAClH,OAAO,CAAC,MAAM,CAEZ;IACF,OAAO,CAAC,UAAU,CAA4D;IAC9E,OAAO,CAAC,YAAY,CAIZ;gBAEI,MAAM,GAAE,oBAAyB;IAQ7C;;OAEG;IACH,MAAM,CAAC,oBAAoB,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,GAAG,CAAA;KAAE,GAAG,MAAM;IAkBpG;;OAEG;IACG,UAAU,CAAC,KAAK,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAsB3C;;OAEG;IACG,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAuEpG"}
|
package/dist/router.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @yumdee/mcp-studio-agent-kit - Semantic Tool Router
|
|
3
|
+
*
|
|
4
|
+
* Dynamic tool retrieval & context pruning using vector embeddings and cosine similarity.
|
|
5
|
+
* Drastically reduces context window bloat and eliminates tool hallucination
|
|
6
|
+
* in multi-server MCP environments with 50+ tools.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Fast cosine similarity between two dense vectors
|
|
10
|
+
*/
|
|
11
|
+
export function cosineSimilarity(a, b) {
|
|
12
|
+
if (a.length !== b.length || a.length === 0)
|
|
13
|
+
return 0;
|
|
14
|
+
let dotProduct = 0;
|
|
15
|
+
let normA = 0;
|
|
16
|
+
let normB = 0;
|
|
17
|
+
for (let i = 0; i < a.length; i++) {
|
|
18
|
+
dotProduct += a[i] * b[i];
|
|
19
|
+
normA += a[i] * a[i];
|
|
20
|
+
normB += b[i] * b[i];
|
|
21
|
+
}
|
|
22
|
+
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
23
|
+
return denom === 0 ? 0 : dotProduct / denom;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Built-in Sub-word & N-Gram Sparse Vectorizer
|
|
27
|
+
* High-speed, zero-dependency semantic vectorizer robust to typos,
|
|
28
|
+
* snake_case/camelCase function identifiers, and terminology variations.
|
|
29
|
+
*/
|
|
30
|
+
export class SparseSemanticVectorizer {
|
|
31
|
+
constructor() {
|
|
32
|
+
this.vocabulary = new Map();
|
|
33
|
+
this.docFrequencies = new Map();
|
|
34
|
+
this.docCount = 0;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Tokenize and normalize text into word stems and character 3-grams
|
|
38
|
+
*/
|
|
39
|
+
tokenize(text) {
|
|
40
|
+
const tokens = [];
|
|
41
|
+
// Split camelCase, snake_case, kebab-case, punctuation
|
|
42
|
+
const words = text
|
|
43
|
+
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
|
44
|
+
.toLowerCase()
|
|
45
|
+
.replace(/[^a-z0-9]/g, " ")
|
|
46
|
+
.split(/\s+/)
|
|
47
|
+
.filter((w) => w.length >= 2);
|
|
48
|
+
for (const word of words) {
|
|
49
|
+
tokens.push(word);
|
|
50
|
+
// Generate character 3-grams for subword matching
|
|
51
|
+
if (word.length >= 3) {
|
|
52
|
+
for (let i = 0; i <= word.length - 3; i++) {
|
|
53
|
+
tokens.push(`__ng_${word.slice(i, i + 3)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return tokens;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Build TF-IDF vocabulary across all documents
|
|
61
|
+
*/
|
|
62
|
+
fit(documents) {
|
|
63
|
+
this.vocabulary.clear();
|
|
64
|
+
this.docFrequencies.clear();
|
|
65
|
+
this.docCount = documents.length;
|
|
66
|
+
let nextIndex = 0;
|
|
67
|
+
for (const doc of documents) {
|
|
68
|
+
const tokens = new Set(this.tokenize(doc));
|
|
69
|
+
for (const token of tokens) {
|
|
70
|
+
if (!this.vocabulary.has(token)) {
|
|
71
|
+
this.vocabulary.set(token, nextIndex++);
|
|
72
|
+
}
|
|
73
|
+
this.docFrequencies.set(token, (this.docFrequencies.get(token) || 0) + 1);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Transform text into a normalized TF-IDF vector
|
|
79
|
+
*/
|
|
80
|
+
transform(text) {
|
|
81
|
+
const vector = new Array(this.vocabulary.size).fill(0);
|
|
82
|
+
const tokens = this.tokenize(text);
|
|
83
|
+
if (tokens.length === 0 || this.vocabulary.size === 0)
|
|
84
|
+
return vector;
|
|
85
|
+
const termCounts = new Map();
|
|
86
|
+
for (const token of tokens) {
|
|
87
|
+
termCounts.set(token, (termCounts.get(token) || 0) + 1);
|
|
88
|
+
}
|
|
89
|
+
let normSq = 0;
|
|
90
|
+
for (const [token, count] of termCounts) {
|
|
91
|
+
const idx = this.vocabulary.get(token);
|
|
92
|
+
if (idx !== undefined) {
|
|
93
|
+
const tf = count / tokens.length;
|
|
94
|
+
const df = this.docFrequencies.get(token) || 1;
|
|
95
|
+
const idf = Math.log((this.docCount + 1) / df) + 1;
|
|
96
|
+
const tfidf = tf * idf;
|
|
97
|
+
vector[idx] = tfidf;
|
|
98
|
+
normSq += tfidf * tfidf;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// L2 Normalize
|
|
102
|
+
const norm = Math.sqrt(normSq);
|
|
103
|
+
if (norm > 0) {
|
|
104
|
+
for (let i = 0; i < vector.length; i++) {
|
|
105
|
+
vector[i] /= norm;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return vector;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Semantic Tool Router
|
|
113
|
+
*/
|
|
114
|
+
export class SemanticToolRouter {
|
|
115
|
+
constructor(config = {}) {
|
|
116
|
+
this.vectorizer = new SparseSemanticVectorizer();
|
|
117
|
+
this.indexedTools = [];
|
|
118
|
+
this.config = {
|
|
119
|
+
topK: config.topK ?? 3,
|
|
120
|
+
minScore: config.minScore ?? 0.08,
|
|
121
|
+
embedFn: config.embedFn,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Convert a tool definition into rich textual signature for vectorization
|
|
126
|
+
*/
|
|
127
|
+
static extractToolSignature(tool) {
|
|
128
|
+
const parts = [tool.name, tool.description || ""];
|
|
129
|
+
const schema = tool.inputSchema;
|
|
130
|
+
if (schema && typeof schema === "object") {
|
|
131
|
+
if (schema.properties && typeof schema.properties === "object") {
|
|
132
|
+
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
133
|
+
parts.push(key);
|
|
134
|
+
if (prop?.description)
|
|
135
|
+
parts.push(prop.description);
|
|
136
|
+
if (prop?.type)
|
|
137
|
+
parts.push(prop.type);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (Array.isArray(schema.required)) {
|
|
141
|
+
parts.push(schema.required.join(" "));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return parts.join(" ");
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Index all tools and build vector space representations
|
|
148
|
+
*/
|
|
149
|
+
async indexTools(tools) {
|
|
150
|
+
this.indexedTools = [];
|
|
151
|
+
const documents = [];
|
|
152
|
+
for (const tool of tools) {
|
|
153
|
+
const signature = SemanticToolRouter.extractToolSignature(tool);
|
|
154
|
+
this.indexedTools.push({ tool, text: signature });
|
|
155
|
+
documents.push(signature);
|
|
156
|
+
}
|
|
157
|
+
if (this.config.embedFn) {
|
|
158
|
+
for (const item of this.indexedTools) {
|
|
159
|
+
item.vector = await this.config.embedFn(item.text);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
this.vectorizer.fit(documents);
|
|
164
|
+
for (const item of this.indexedTools) {
|
|
165
|
+
item.vector = this.vectorizer.transform(item.text);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Semantically route a user query to the top-K relevant tools
|
|
171
|
+
*/
|
|
172
|
+
async route(query, options) {
|
|
173
|
+
const topK = options?.topK ?? this.config.topK;
|
|
174
|
+
const minScore = options?.minScore ?? this.config.minScore;
|
|
175
|
+
if (this.indexedTools.length === 0) {
|
|
176
|
+
return {
|
|
177
|
+
selectedTools: [],
|
|
178
|
+
scores: [],
|
|
179
|
+
metrics: {
|
|
180
|
+
totalTools: 0,
|
|
181
|
+
selectedCount: 0,
|
|
182
|
+
prunedCount: 0,
|
|
183
|
+
estimatedTokensBefore: 0,
|
|
184
|
+
estimatedTokensAfter: 0,
|
|
185
|
+
tokensSaved: 0,
|
|
186
|
+
reductionPercentage: 0,
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
// Compute query vector
|
|
191
|
+
const queryVector = this.config.embedFn
|
|
192
|
+
? await this.config.embedFn(query)
|
|
193
|
+
: this.vectorizer.transform(query);
|
|
194
|
+
// Score all tools
|
|
195
|
+
const scored = this.indexedTools.map((item) => {
|
|
196
|
+
const score = item.vector ? cosineSimilarity(queryVector, item.vector) : 0;
|
|
197
|
+
return { tool: item.tool, toolName: item.tool.name, score };
|
|
198
|
+
});
|
|
199
|
+
// Sort descending by score
|
|
200
|
+
scored.sort((a, b) => b.score - a.score);
|
|
201
|
+
// Filter by threshold and take top-K
|
|
202
|
+
let selected = scored.filter((item) => item.score >= minScore).slice(0, topK);
|
|
203
|
+
// Fallback: If no tools pass the threshold, return the single highest scoring tool if score > 0
|
|
204
|
+
if (selected.length === 0 && scored.length > 0 && scored[0].score > 0) {
|
|
205
|
+
selected = [scored[0]];
|
|
206
|
+
}
|
|
207
|
+
// If still empty (e.g. zero similarity everywhere), keep top-1 as safety fallback
|
|
208
|
+
if (selected.length === 0 && scored.length > 0) {
|
|
209
|
+
selected = [scored[0]];
|
|
210
|
+
}
|
|
211
|
+
// Estimate token metrics (approx 150 tokens per tool schema definition in JSON)
|
|
212
|
+
const tokensPerTool = 180;
|
|
213
|
+
const estimatedTokensBefore = this.indexedTools.length * tokensPerTool;
|
|
214
|
+
const estimatedTokensAfter = selected.length * tokensPerTool;
|
|
215
|
+
const tokensSaved = Math.max(0, estimatedTokensBefore - estimatedTokensAfter);
|
|
216
|
+
const reductionPercentage = estimatedTokensBefore > 0
|
|
217
|
+
? Math.round((tokensSaved / estimatedTokensBefore) * 100)
|
|
218
|
+
: 0;
|
|
219
|
+
return {
|
|
220
|
+
selectedTools: selected.map((s) => s.tool),
|
|
221
|
+
scores: scored.map((s) => ({ toolName: s.toolName, score: Math.round(s.score * 1000) / 1000 })),
|
|
222
|
+
metrics: {
|
|
223
|
+
totalTools: this.indexedTools.length,
|
|
224
|
+
selectedCount: selected.length,
|
|
225
|
+
prunedCount: this.indexedTools.length - selected.length,
|
|
226
|
+
estimatedTokensBefore,
|
|
227
|
+
estimatedTokensAfter,
|
|
228
|
+
tokensSaved,
|
|
229
|
+
reductionPercentage,
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;A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AM,mBAAmB,GACvB,qBAAqB,GAAG,CAAC;YACvB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,WAAW,GAAG,qBAAqB,CAAC,GAAG,GAAG,CAAC;YACzD,CAAC,CAAC,CAAC,CAAC;QAER,OAAO;YACL,aAAa,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;YAC1C,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;YAC/F,OAAO,EAAE;gBACP,UAAU,EAAE,IAAI,CAAC,YAAY,CAAC,MAAM;gBACpC,aAAa,EAAE,QAAQ,CAAC,MAAM;gBAC9B,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM;gBACvD,qBAAqB;gBACrB,oBAAoB;gBACpB,WAAW;gBACX,mBAAmB;aACpB;SACF,CAAC;IACJ,CAAC;CACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@yumdee/mcp-studio-agent-kit",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Orchestration layer for chaining multiple MCP servers",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md"
|
|
11
|
+
],
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/maheshsingh20/YumDee-MCP-Studio.git",
|
|
18
|
+
"directory": "packages/agent-kit"
|
|
19
|
+
},
|
|
20
|
+
"author": "Mahesh Singh <maheshsingh20>",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@yumdee/mcp-studio-core": "0.1.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^20.0.0",
|
|
27
|
+
"typescript": "^5.3.0",
|
|
28
|
+
"vitest": "^1.0.0"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"dev": "tsc --watch --incremental",
|
|
32
|
+
"build": "tsc",
|
|
33
|
+
"type-check": "tsc --noEmit",
|
|
34
|
+
"lint": "eslint src/",
|
|
35
|
+
"test": "vitest run"
|
|
36
|
+
}
|
|
37
|
+
}
|