openloops 0.2.3 → 0.2.6
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/README.md +8 -1
- package/dist/clients/slack/index.d.ts +1 -0
- package/dist/clients/slack/index.js +22 -0
- package/dist/clients/slack/index.mjs +1 -0
- package/dist/clients/slack/slack-client.d.ts +11 -0
- package/dist/clients/slack/slack-client.js +50 -0
- package/dist/clients/slack/slack-client.mjs +27 -0
- package/dist/harness/agent.d.ts +15 -0
- package/dist/harness/agent.js +62 -4
- package/dist/harness/agent.mjs +62 -4
- package/dist/services/agentic-jobs/runner/agentic-job-runner.js +3 -1
- package/dist/services/agentic-jobs/runner/agentic-job-runner.mjs +3 -1
- package/dist/tools/core/index.d.ts +1 -0
- package/dist/tools/core/index.js +3 -1
- package/dist/tools/core/index.mjs +1 -0
- package/dist/tools/core/slack/index.d.ts +1 -0
- package/dist/tools/core/slack/index.js +22 -0
- package/dist/tools/core/slack/index.mjs +1 -0
- package/dist/tools/core/slack/send-slack-message.tool.d.ts +2 -0
- package/dist/tools/core/slack/send-slack-message.tool.js +54 -0
- package/dist/tools/core/slack/send-slack-message.tool.mjs +31 -0
- package/dist/tools/tool.d.ts +1 -0
- package/dist/tools/tool.js +1 -1
- package/dist/tools/tool.mjs +1 -1
- package/docs/agent.md +3 -0
- package/docs/agentic-jobs.md +10 -0
- package/docs/configuration.md +2 -0
- package/docs/llms.txt +1 -1
- package/docs/mcp-servers.md +38 -0
- package/docs/tools.md +12 -0
- package/examples/mcps/internal-mcp.ts +38 -0
- package/examples/run-agent/run-agent-with-slack.ts +32 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -150,6 +150,8 @@ await createMcpServer({
|
|
|
150
150
|
|
|
151
151
|
The next time that user talks to *any* agent, the server is there. The first time one of its tools is about to run, the agent asks the user to approve it.
|
|
152
152
|
|
|
153
|
+
An MCP server of your own solution, one the user never sees, is declared in code with `internalMcps` and called with the token of the user in each run. See [MCP servers](docs/mcp-servers.md#internal-mcp-servers).
|
|
154
|
+
|
|
153
155
|
Blocking sensitive input:
|
|
154
156
|
|
|
155
157
|
```typescript
|
|
@@ -228,8 +230,9 @@ LANGFUSE_SECRET_KEY=
|
|
|
228
230
|
LANGFUSE_PUBLIC_KEY=
|
|
229
231
|
LANGFUSE_BASE_URL=
|
|
230
232
|
|
|
231
|
-
# Optional, see "Web search" below
|
|
233
|
+
# Optional, see "Web search" and "Slack" below
|
|
232
234
|
SERPER_API_KEY=
|
|
235
|
+
SLACK_BOT_TOKEN=
|
|
233
236
|
```
|
|
234
237
|
|
|
235
238
|
Every variable is described in [`docs/configuration.md`](docs/configuration.md).
|
|
@@ -242,6 +245,10 @@ By default, `openloops` uses a database named `openloops` if `OPENLOOPS_DB_NAME`
|
|
|
242
245
|
|
|
243
246
|
The built-in `webSearchTool` uses [Serper](https://serper.dev). Create a free API key there and set `SERPER_API_KEY` in your `.env`. See [`docs/tools.md`](docs/tools.md).
|
|
244
247
|
|
|
248
|
+
### Slack
|
|
249
|
+
|
|
250
|
+
The built-in `sendSlackMessageTool` posts a message to a channel. Create a Slack app with the `chat:write` scope, install it in your workspace, invite the bot to the channel and set `SLACK_BOT_TOKEN` in your `.env`. See [`docs/tools.md`](docs/tools.md).
|
|
251
|
+
|
|
245
252
|
### Observability
|
|
246
253
|
|
|
247
254
|
- **Sentry**: set `SENTRY_DSN` and error tracking turns on automatically.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './slack-client';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __copyProps = (to, from, except, desc) => {
|
|
7
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
+
for (let key of __getOwnPropNames(from))
|
|
9
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
+
}
|
|
12
|
+
return to;
|
|
13
|
+
};
|
|
14
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
15
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
|
+
var slack_exports = {};
|
|
17
|
+
module.exports = __toCommonJS(slack_exports);
|
|
18
|
+
__reExport(slack_exports, require("./slack-client"), module.exports);
|
|
19
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
20
|
+
0 && (module.exports = {
|
|
21
|
+
...require("./slack-client")
|
|
22
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./slack-client";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface SlackMessage {
|
|
2
|
+
channel: string;
|
|
3
|
+
text: string;
|
|
4
|
+
}
|
|
5
|
+
export interface SlackSentMessage {
|
|
6
|
+
channel: string;
|
|
7
|
+
ts: string;
|
|
8
|
+
}
|
|
9
|
+
export declare class SlackClient {
|
|
10
|
+
sendMessage({ channel, text }: SlackMessage): Promise<SlackSentMessage>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var slack_client_exports = {};
|
|
20
|
+
__export(slack_client_exports, {
|
|
21
|
+
SlackClient: () => SlackClient
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(slack_client_exports);
|
|
24
|
+
var import_secret_manager = require("../../common/utils/secret-manager.js");
|
|
25
|
+
class SlackClient {
|
|
26
|
+
async sendMessage({ channel, text }) {
|
|
27
|
+
const token = import_secret_manager.secretManager.get("SLACK_BOT_TOKEN");
|
|
28
|
+
if (!token) throw new Error("[Slack Client] SLACK_BOT_TOKEN is not set");
|
|
29
|
+
const response = await fetch("https://slack.com/api/chat.postMessage", {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
Authorization: `Bearer ${token}`,
|
|
33
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
34
|
+
},
|
|
35
|
+
body: JSON.stringify({ channel, text, mrkdwn: true, unfurl_links: true, unfurl_media: true })
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
throw new Error(`[Slack Client] Slack responded with status ${response.status}`);
|
|
39
|
+
}
|
|
40
|
+
const data = await response.json();
|
|
41
|
+
if (!data.ok) {
|
|
42
|
+
throw new Error(`[Slack Client] ${data.error ?? "unknown_error"}`);
|
|
43
|
+
}
|
|
44
|
+
return { channel: data.channel, ts: data.ts };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
48
|
+
0 && (module.exports = {
|
|
49
|
+
SlackClient
|
|
50
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "../../chunk-CF3WOMB3.mjs";
|
|
2
|
+
import { secretManager } from "../../common/utils/secret-manager.js";
|
|
3
|
+
class SlackClient {
|
|
4
|
+
async sendMessage({ channel, text }) {
|
|
5
|
+
const token = secretManager.get("SLACK_BOT_TOKEN");
|
|
6
|
+
if (!token) throw new Error("[Slack Client] SLACK_BOT_TOKEN is not set");
|
|
7
|
+
const response = await fetch("https://slack.com/api/chat.postMessage", {
|
|
8
|
+
method: "POST",
|
|
9
|
+
headers: {
|
|
10
|
+
Authorization: `Bearer ${token}`,
|
|
11
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
12
|
+
},
|
|
13
|
+
body: JSON.stringify({ channel, text, mrkdwn: true, unfurl_links: true, unfurl_media: true })
|
|
14
|
+
});
|
|
15
|
+
if (!response.ok) {
|
|
16
|
+
throw new Error(`[Slack Client] Slack responded with status ${response.status}`);
|
|
17
|
+
}
|
|
18
|
+
const data = await response.json();
|
|
19
|
+
if (!data.ok) {
|
|
20
|
+
throw new Error(`[Slack Client] ${data.error ?? "unknown_error"}`);
|
|
21
|
+
}
|
|
22
|
+
return { channel: data.channel, ts: data.ts };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
SlackClient
|
|
27
|
+
};
|
package/dist/harness/agent.d.ts
CHANGED
|
@@ -6,6 +6,11 @@ import { ChatSettingsProps } from '../services/chats/entities/chat-settings.enti
|
|
|
6
6
|
import { Tool } from '../tools/tool.js';
|
|
7
7
|
import { Guard } from '../guardrails/guard.js';
|
|
8
8
|
import { AgentLoop } from './agent-loop';
|
|
9
|
+
export interface InternalMcp {
|
|
10
|
+
name: string;
|
|
11
|
+
url: string;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
}
|
|
9
14
|
export declare const AGENT_ERROR_CODES: {
|
|
10
15
|
readonly NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND";
|
|
11
16
|
readonly RUN_FAILED: "AGENT_RUN_FAILED";
|
|
@@ -19,6 +24,7 @@ interface AgentIdentity {
|
|
|
19
24
|
export interface AgentOptions {
|
|
20
25
|
loop: AgentLoop;
|
|
21
26
|
tools?: Tool[];
|
|
27
|
+
internalMcps?: InternalMcp[];
|
|
22
28
|
guards?: Guard[];
|
|
23
29
|
maxInputLength?: number;
|
|
24
30
|
identity?: AgentIdentity;
|
|
@@ -44,7 +50,10 @@ export declare class Agent {
|
|
|
44
50
|
private readonly fallbackModel?;
|
|
45
51
|
private model?;
|
|
46
52
|
private _tools;
|
|
53
|
+
private _internalMcps;
|
|
47
54
|
private _mcps;
|
|
55
|
+
private mcpTokens;
|
|
56
|
+
private serviceToken?;
|
|
48
57
|
private mcpListing?;
|
|
49
58
|
private mcpListingFailed;
|
|
50
59
|
private _preHooks;
|
|
@@ -79,6 +88,8 @@ export declare class Agent {
|
|
|
79
88
|
options?: ChatSettingsProps;
|
|
80
89
|
currentUser: CurrentUser;
|
|
81
90
|
currentSession?: CurrentSession;
|
|
91
|
+
mcpTokens?: Record<string, string>;
|
|
92
|
+
serviceToken?: string;
|
|
82
93
|
}): Promise<{
|
|
83
94
|
data: Chat;
|
|
84
95
|
error?: undefined;
|
|
@@ -88,6 +99,7 @@ export declare class Agent {
|
|
|
88
99
|
}>;
|
|
89
100
|
stopAgent(): void;
|
|
90
101
|
addTool(tool: Tool): void;
|
|
102
|
+
addInternalMcp(mcp: InternalMcp): void;
|
|
91
103
|
addHook(type: HookType, fn: Function): void;
|
|
92
104
|
addGuard(guard: Guard): void;
|
|
93
105
|
private preRunner;
|
|
@@ -108,6 +120,9 @@ export declare class Agent {
|
|
|
108
120
|
private ensureTools;
|
|
109
121
|
private listMcps;
|
|
110
122
|
private toMcpEntry;
|
|
123
|
+
private toInternalEntry;
|
|
124
|
+
private resolveInternalHeaders;
|
|
125
|
+
private mask;
|
|
111
126
|
private mcpIndex;
|
|
112
127
|
private entryOf;
|
|
113
128
|
private isGatedEntry;
|
package/dist/harness/agent.js
CHANGED
|
@@ -48,6 +48,8 @@ var import_llm_error = require("../clients/llm/llm-error.js");
|
|
|
48
48
|
var import_model_resolution = require("../clients/llm/model-resolution.js");
|
|
49
49
|
const MCP_CONNECT_RETRY_DELAYS_MS = [1e3, 2e3];
|
|
50
50
|
const MCP_DESCRIPTION_CHARS = 300;
|
|
51
|
+
const TOKEN_PLACEHOLDER = "{{token}}";
|
|
52
|
+
const USER_ID_HEADER = "X-User-Id";
|
|
51
53
|
const MAX_AUTOMATIC_ANSWERS = 3;
|
|
52
54
|
const AUTOMATIC_ANSWER_RESULTS = 5;
|
|
53
55
|
const AUTOMATIC_ANSWER_RESULT_CHARS = 1500;
|
|
@@ -66,7 +68,10 @@ class Agent {
|
|
|
66
68
|
fallbackModel;
|
|
67
69
|
model;
|
|
68
70
|
_tools;
|
|
71
|
+
_internalMcps = [];
|
|
69
72
|
_mcps = [];
|
|
73
|
+
mcpTokens = {};
|
|
74
|
+
serviceToken;
|
|
70
75
|
mcpListing;
|
|
71
76
|
mcpListingFailed = false;
|
|
72
77
|
_preHooks = [];
|
|
@@ -114,6 +119,7 @@ class Agent {
|
|
|
114
119
|
this._identity = agentOptions.identity;
|
|
115
120
|
this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
116
121
|
this.strictMode = agentOptions.strictMode ?? false;
|
|
122
|
+
for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
|
|
117
123
|
if (agentOptions.fallbackModel) {
|
|
118
124
|
this.fallbackModel = (0, import_model_resolution.toModelRef)(agentOptions.fallbackModel);
|
|
119
125
|
if (!this.fallbackModel) throw new Error("[AGENT] fallbackModel needs a provider and a model");
|
|
@@ -140,7 +146,7 @@ class Agent {
|
|
|
140
146
|
}
|
|
141
147
|
async run(props) {
|
|
142
148
|
try {
|
|
143
|
-
const { input, options, currentUser, currentSession } = props || {};
|
|
149
|
+
const { input, options, currentUser, currentSession, mcpTokens, serviceToken } = props || {};
|
|
144
150
|
const { chatId, message } = input || {};
|
|
145
151
|
this.logger.debug(input, "[AGENT] Agent started");
|
|
146
152
|
if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
|
|
@@ -163,6 +169,8 @@ class Agent {
|
|
|
163
169
|
this.currentSession = currentSession;
|
|
164
170
|
this.currentMessage = message;
|
|
165
171
|
this.chatOptions = options;
|
|
172
|
+
this.mcpTokens = mcpTokens ?? {};
|
|
173
|
+
this.serviceToken = serviceToken;
|
|
166
174
|
this.model = void 0;
|
|
167
175
|
if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
|
|
168
176
|
this.answerId = new import_mongodb.ObjectId().toString();
|
|
@@ -189,6 +197,11 @@ class Agent {
|
|
|
189
197
|
addTool(tool) {
|
|
190
198
|
this._tools.push(tool);
|
|
191
199
|
}
|
|
200
|
+
addInternalMcp(mcp) {
|
|
201
|
+
if (!mcp?.name || !mcp?.url) throw new Error("[AGENT] An internal MCP needs a name and a url");
|
|
202
|
+
if (this._internalMcps.some((candidate) => candidate.name === mcp.name)) throw new Error(`[AGENT] There is already an internal MCP named "${mcp.name}"`);
|
|
203
|
+
this._internalMcps.push(mcp);
|
|
204
|
+
}
|
|
192
205
|
addHook(type, fn) {
|
|
193
206
|
if (type === "pre_execution") this._preHooks.push(fn);
|
|
194
207
|
if (type === "post_execution") this._postHooks.push(fn);
|
|
@@ -456,9 +469,17 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
456
469
|
}
|
|
457
470
|
async listMcps() {
|
|
458
471
|
if (!this.currentUser) return;
|
|
472
|
+
this._mcps = this._internalMcps.map((mcp) => this.toInternalEntry(mcp));
|
|
459
473
|
try {
|
|
460
474
|
const response = await (0, import_mcp_servers.listAllMcpServersByUser)({ currentUser: this.currentUser });
|
|
461
|
-
|
|
475
|
+
const reserved = new Set(this._internalMcps.map((mcp) => mcp.name));
|
|
476
|
+
const stored = (response?.data ?? []).filter((props) => {
|
|
477
|
+
if (!reserved.has(props.name)) return true;
|
|
478
|
+
this.logger.error({ mcpServer: props.name }, "[AGENT] A server of the user was ignored because its name belongs to an internal MCP");
|
|
479
|
+
this.currentChat?.addTrace({ node: "agent", kind: "agent", reasoning: `A server of the user was ignored because its name belongs to an internal MCP: ${props.name}` });
|
|
480
|
+
return false;
|
|
481
|
+
});
|
|
482
|
+
this._mcps.push(...stored.map((props) => this.toMcpEntry(props)));
|
|
462
483
|
} catch (error) {
|
|
463
484
|
this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to list MCP servers");
|
|
464
485
|
this.mcpListingFailed = true;
|
|
@@ -468,8 +489,40 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
468
489
|
const server = import_entities.McpServer.fromJSON(props);
|
|
469
490
|
return { id: String(props._id ?? ""), name: props.name ?? "mcp", server, tools: [], access: server.trust === "blocked" ? "blocked" : "not_connected" };
|
|
470
491
|
}
|
|
492
|
+
toInternalEntry(mcp) {
|
|
493
|
+
const headers = this.resolveInternalHeaders(mcp);
|
|
494
|
+
const server = import_entities.McpServer.fromJSON({ name: mcp.name, url: mcp.url, type: "http", headers });
|
|
495
|
+
const entry = { id: "", name: mcp.name, internal: true, server, tools: [], access: "not_connected" };
|
|
496
|
+
if (!headers) {
|
|
497
|
+
entry.access = "unavailable";
|
|
498
|
+
entry.connection = Promise.resolve();
|
|
499
|
+
this.logger.error({ mcpServer: mcp.name }, "[AGENT] There is no token for the internal MCP");
|
|
500
|
+
this.currentChat?.addTrace({ node: "agent", kind: "agent", reasoning: `Tool source unavailable: ${mcp.name} (no token for this run)` });
|
|
501
|
+
}
|
|
502
|
+
return entry;
|
|
503
|
+
}
|
|
504
|
+
resolveInternalHeaders(mcp) {
|
|
505
|
+
const headers = { ...mcp.headers };
|
|
506
|
+
if (!Object.values(headers).some((value) => value.includes(TOKEN_PLACEHOLDER))) return headers;
|
|
507
|
+
const own = this.mcpTokens[mcp.name];
|
|
508
|
+
const token = own || this.serviceToken;
|
|
509
|
+
const userId = this.currentUser?.userId;
|
|
510
|
+
if (!token || !userId) return void 0;
|
|
511
|
+
for (const [name, value] of Object.entries(headers)) headers[name] = value.split(TOKEN_PLACEHOLDER).join(token);
|
|
512
|
+
if (!own) {
|
|
513
|
+
for (const name of Object.keys(headers)) if (name.toLowerCase() === USER_ID_HEADER.toLowerCase()) delete headers[name];
|
|
514
|
+
headers[USER_ID_HEADER] = userId;
|
|
515
|
+
}
|
|
516
|
+
return headers;
|
|
517
|
+
}
|
|
518
|
+
mask(error) {
|
|
519
|
+
let text = error instanceof Error ? error.message : String(error);
|
|
520
|
+
for (const secret of [...Object.values(this.mcpTokens), this.serviceToken]) if (secret) text = text.split(secret).join("***");
|
|
521
|
+
return text;
|
|
522
|
+
}
|
|
471
523
|
mcpIndex() {
|
|
472
524
|
return this._mcps.map((entry) => {
|
|
525
|
+
if (entry.internal) return { name: entry.name, state: "approved" };
|
|
473
526
|
if (entry.access === "blocked") return { name: entry.name, state: "blocked" };
|
|
474
527
|
const approved = entry.access === "ready" || ["not_connected", "unavailable"].includes(entry.access) && entry.server.trust === "approved";
|
|
475
528
|
const description = entry.server.latest?.instructions?.slice(0, MCP_DESCRIPTION_CHARS);
|
|
@@ -501,11 +554,16 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
501
554
|
try {
|
|
502
555
|
const client = await entry.server.connect();
|
|
503
556
|
const { manifest, tools } = await entry.server.inspect(client);
|
|
504
|
-
entry.tools = tools.map((tool) => import_tool.Tool.fromMcp(tool, client, { namespace: entry.name }));
|
|
557
|
+
entry.tools = tools.map((tool) => import_tool.Tool.fromMcp(tool, client, { namespace: entry.name, internal: entry.internal }));
|
|
558
|
+
if (entry.internal) {
|
|
559
|
+
entry.hash = manifest.hash;
|
|
560
|
+
entry.access = "ready";
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
505
563
|
await this.reviewMcp(entry, manifest);
|
|
506
564
|
return;
|
|
507
565
|
} catch (error) {
|
|
508
|
-
this.logger.error({ error, mcpServer: entry.name, attempt: attempt + 1 }, "[AGENT] Failed to connect MCP server");
|
|
566
|
+
this.logger.error({ error: entry.internal ? this.mask(error) : error, mcpServer: entry.name, attempt: attempt + 1 }, "[AGENT] Failed to connect MCP server");
|
|
509
567
|
await Promise.resolve().then(() => entry.server.disconnect()).catch(() => void 0);
|
|
510
568
|
const delay = MCP_CONNECT_RETRY_DELAYS_MS[attempt];
|
|
511
569
|
if (delay === void 0) break;
|
package/dist/harness/agent.mjs
CHANGED
|
@@ -33,6 +33,8 @@ import { LLMError } from "../clients/llm/llm-error.js";
|
|
|
33
33
|
import { resolveModel, toModelRef } from "../clients/llm/model-resolution.js";
|
|
34
34
|
const MCP_CONNECT_RETRY_DELAYS_MS = [1e3, 2e3];
|
|
35
35
|
const MCP_DESCRIPTION_CHARS = 300;
|
|
36
|
+
const TOKEN_PLACEHOLDER = "{{token}}";
|
|
37
|
+
const USER_ID_HEADER = "X-User-Id";
|
|
36
38
|
const MAX_AUTOMATIC_ANSWERS = 3;
|
|
37
39
|
const AUTOMATIC_ANSWER_RESULTS = 5;
|
|
38
40
|
const AUTOMATIC_ANSWER_RESULT_CHARS = 1500;
|
|
@@ -51,7 +53,10 @@ class Agent {
|
|
|
51
53
|
fallbackModel;
|
|
52
54
|
model;
|
|
53
55
|
_tools;
|
|
56
|
+
_internalMcps = [];
|
|
54
57
|
_mcps = [];
|
|
58
|
+
mcpTokens = {};
|
|
59
|
+
serviceToken;
|
|
55
60
|
mcpListing;
|
|
56
61
|
mcpListingFailed = false;
|
|
57
62
|
_preHooks = [];
|
|
@@ -99,6 +104,7 @@ class Agent {
|
|
|
99
104
|
this._identity = agentOptions.identity;
|
|
100
105
|
this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
101
106
|
this.strictMode = agentOptions.strictMode ?? false;
|
|
107
|
+
for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
|
|
102
108
|
if (agentOptions.fallbackModel) {
|
|
103
109
|
this.fallbackModel = toModelRef(agentOptions.fallbackModel);
|
|
104
110
|
if (!this.fallbackModel) throw new Error("[AGENT] fallbackModel needs a provider and a model");
|
|
@@ -125,7 +131,7 @@ class Agent {
|
|
|
125
131
|
}
|
|
126
132
|
async run(props) {
|
|
127
133
|
try {
|
|
128
|
-
const { input, options, currentUser, currentSession } = props || {};
|
|
134
|
+
const { input, options, currentUser, currentSession, mcpTokens, serviceToken } = props || {};
|
|
129
135
|
const { chatId, message } = input || {};
|
|
130
136
|
this.logger.debug(input, "[AGENT] Agent started");
|
|
131
137
|
if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
|
|
@@ -148,6 +154,8 @@ class Agent {
|
|
|
148
154
|
this.currentSession = currentSession;
|
|
149
155
|
this.currentMessage = message;
|
|
150
156
|
this.chatOptions = options;
|
|
157
|
+
this.mcpTokens = mcpTokens ?? {};
|
|
158
|
+
this.serviceToken = serviceToken;
|
|
151
159
|
this.model = void 0;
|
|
152
160
|
if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
|
|
153
161
|
this.answerId = new ObjectId().toString();
|
|
@@ -174,6 +182,11 @@ class Agent {
|
|
|
174
182
|
addTool(tool) {
|
|
175
183
|
this._tools.push(tool);
|
|
176
184
|
}
|
|
185
|
+
addInternalMcp(mcp) {
|
|
186
|
+
if (!mcp?.name || !mcp?.url) throw new Error("[AGENT] An internal MCP needs a name and a url");
|
|
187
|
+
if (this._internalMcps.some((candidate) => candidate.name === mcp.name)) throw new Error(`[AGENT] There is already an internal MCP named "${mcp.name}"`);
|
|
188
|
+
this._internalMcps.push(mcp);
|
|
189
|
+
}
|
|
177
190
|
addHook(type, fn) {
|
|
178
191
|
if (type === "pre_execution") this._preHooks.push(fn);
|
|
179
192
|
if (type === "post_execution") this._postHooks.push(fn);
|
|
@@ -441,9 +454,17 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
441
454
|
}
|
|
442
455
|
async listMcps() {
|
|
443
456
|
if (!this.currentUser) return;
|
|
457
|
+
this._mcps = this._internalMcps.map((mcp) => this.toInternalEntry(mcp));
|
|
444
458
|
try {
|
|
445
459
|
const response = await listAllMcpServersByUser({ currentUser: this.currentUser });
|
|
446
|
-
|
|
460
|
+
const reserved = new Set(this._internalMcps.map((mcp) => mcp.name));
|
|
461
|
+
const stored = (response?.data ?? []).filter((props) => {
|
|
462
|
+
if (!reserved.has(props.name)) return true;
|
|
463
|
+
this.logger.error({ mcpServer: props.name }, "[AGENT] A server of the user was ignored because its name belongs to an internal MCP");
|
|
464
|
+
this.currentChat?.addTrace({ node: "agent", kind: "agent", reasoning: `A server of the user was ignored because its name belongs to an internal MCP: ${props.name}` });
|
|
465
|
+
return false;
|
|
466
|
+
});
|
|
467
|
+
this._mcps.push(...stored.map((props) => this.toMcpEntry(props)));
|
|
447
468
|
} catch (error) {
|
|
448
469
|
this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to list MCP servers");
|
|
449
470
|
this.mcpListingFailed = true;
|
|
@@ -453,8 +474,40 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
453
474
|
const server = McpServer.fromJSON(props);
|
|
454
475
|
return { id: String(props._id ?? ""), name: props.name ?? "mcp", server, tools: [], access: server.trust === "blocked" ? "blocked" : "not_connected" };
|
|
455
476
|
}
|
|
477
|
+
toInternalEntry(mcp) {
|
|
478
|
+
const headers = this.resolveInternalHeaders(mcp);
|
|
479
|
+
const server = McpServer.fromJSON({ name: mcp.name, url: mcp.url, type: "http", headers });
|
|
480
|
+
const entry = { id: "", name: mcp.name, internal: true, server, tools: [], access: "not_connected" };
|
|
481
|
+
if (!headers) {
|
|
482
|
+
entry.access = "unavailable";
|
|
483
|
+
entry.connection = Promise.resolve();
|
|
484
|
+
this.logger.error({ mcpServer: mcp.name }, "[AGENT] There is no token for the internal MCP");
|
|
485
|
+
this.currentChat?.addTrace({ node: "agent", kind: "agent", reasoning: `Tool source unavailable: ${mcp.name} (no token for this run)` });
|
|
486
|
+
}
|
|
487
|
+
return entry;
|
|
488
|
+
}
|
|
489
|
+
resolveInternalHeaders(mcp) {
|
|
490
|
+
const headers = { ...mcp.headers };
|
|
491
|
+
if (!Object.values(headers).some((value) => value.includes(TOKEN_PLACEHOLDER))) return headers;
|
|
492
|
+
const own = this.mcpTokens[mcp.name];
|
|
493
|
+
const token = own || this.serviceToken;
|
|
494
|
+
const userId = this.currentUser?.userId;
|
|
495
|
+
if (!token || !userId) return void 0;
|
|
496
|
+
for (const [name, value] of Object.entries(headers)) headers[name] = value.split(TOKEN_PLACEHOLDER).join(token);
|
|
497
|
+
if (!own) {
|
|
498
|
+
for (const name of Object.keys(headers)) if (name.toLowerCase() === USER_ID_HEADER.toLowerCase()) delete headers[name];
|
|
499
|
+
headers[USER_ID_HEADER] = userId;
|
|
500
|
+
}
|
|
501
|
+
return headers;
|
|
502
|
+
}
|
|
503
|
+
mask(error) {
|
|
504
|
+
let text = error instanceof Error ? error.message : String(error);
|
|
505
|
+
for (const secret of [...Object.values(this.mcpTokens), this.serviceToken]) if (secret) text = text.split(secret).join("***");
|
|
506
|
+
return text;
|
|
507
|
+
}
|
|
456
508
|
mcpIndex() {
|
|
457
509
|
return this._mcps.map((entry) => {
|
|
510
|
+
if (entry.internal) return { name: entry.name, state: "approved" };
|
|
458
511
|
if (entry.access === "blocked") return { name: entry.name, state: "blocked" };
|
|
459
512
|
const approved = entry.access === "ready" || ["not_connected", "unavailable"].includes(entry.access) && entry.server.trust === "approved";
|
|
460
513
|
const description = entry.server.latest?.instructions?.slice(0, MCP_DESCRIPTION_CHARS);
|
|
@@ -486,11 +539,16 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
|
|
|
486
539
|
try {
|
|
487
540
|
const client = await entry.server.connect();
|
|
488
541
|
const { manifest, tools } = await entry.server.inspect(client);
|
|
489
|
-
entry.tools = tools.map((tool) => Tool.fromMcp(tool, client, { namespace: entry.name }));
|
|
542
|
+
entry.tools = tools.map((tool) => Tool.fromMcp(tool, client, { namespace: entry.name, internal: entry.internal }));
|
|
543
|
+
if (entry.internal) {
|
|
544
|
+
entry.hash = manifest.hash;
|
|
545
|
+
entry.access = "ready";
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
490
548
|
await this.reviewMcp(entry, manifest);
|
|
491
549
|
return;
|
|
492
550
|
} catch (error) {
|
|
493
|
-
this.logger.error({ error, mcpServer: entry.name, attempt: attempt + 1 }, "[AGENT] Failed to connect MCP server");
|
|
551
|
+
this.logger.error({ error: entry.internal ? this.mask(error) : error, mcpServer: entry.name, attempt: attempt + 1 }, "[AGENT] Failed to connect MCP server");
|
|
494
552
|
await Promise.resolve().then(() => entry.server.disconnect()).catch(() => void 0);
|
|
495
553
|
const delay = MCP_CONNECT_RETRY_DELAYS_MS[attempt];
|
|
496
554
|
if (delay === void 0) break;
|
|
@@ -25,6 +25,7 @@ module.exports = __toCommonJS(agentic_job_runner_exports);
|
|
|
25
25
|
var import_node_crypto = require("node:crypto");
|
|
26
26
|
var import_node_os = require("node:os");
|
|
27
27
|
var import_logger = require("../../../common/logger/index.js");
|
|
28
|
+
var import_secret_manager = require("../../../common/utils/secret-manager.js");
|
|
28
29
|
var import_base = require("../../../common/base/index.js");
|
|
29
30
|
var import_agent = require("../../../harness/agent.js");
|
|
30
31
|
var import_loop = require("../../../loops/agi/loop.js");
|
|
@@ -151,7 +152,8 @@ class AgenticJobRunner {
|
|
|
151
152
|
input: { message: job.instructions, chatId },
|
|
152
153
|
options: { executionMode: "autonomous", ...model },
|
|
153
154
|
currentUser,
|
|
154
|
-
currentSession: import_base.CurrentSession.fromJSON({ location: { timezone: job.timezone } })
|
|
155
|
+
currentSession: import_base.CurrentSession.fromJSON({ location: { timezone: job.timezone } }),
|
|
156
|
+
serviceToken: process.env.INTERNAL_MCP_TOKEN ? import_secret_manager.secretManager.get("INTERNAL_MCP_TOKEN") : void 0
|
|
155
157
|
});
|
|
156
158
|
const chat = result.data;
|
|
157
159
|
const state = chat?.state;
|
|
@@ -2,6 +2,7 @@ import "../../../chunk-CF3WOMB3.mjs";
|
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
4
|
import { Logger } from "../../../common/logger/index.js";
|
|
5
|
+
import { secretManager } from "../../../common/utils/secret-manager.js";
|
|
5
6
|
import { CurrentUser, CurrentSession } from "../../../common/base/index.js";
|
|
6
7
|
import { Agent } from "../../../harness/agent.js";
|
|
7
8
|
import { AgiLoop } from "../../../loops/agi/loop.js";
|
|
@@ -128,7 +129,8 @@ class AgenticJobRunner {
|
|
|
128
129
|
input: { message: job.instructions, chatId },
|
|
129
130
|
options: { executionMode: "autonomous", ...model },
|
|
130
131
|
currentUser,
|
|
131
|
-
currentSession: CurrentSession.fromJSON({ location: { timezone: job.timezone } })
|
|
132
|
+
currentSession: CurrentSession.fromJSON({ location: { timezone: job.timezone } }),
|
|
133
|
+
serviceToken: process.env.INTERNAL_MCP_TOKEN ? secretManager.get("INTERNAL_MCP_TOKEN") : void 0
|
|
132
134
|
});
|
|
133
135
|
const chat = result.data;
|
|
134
136
|
const state = chat?.state;
|
package/dist/tools/core/index.js
CHANGED
|
@@ -17,8 +17,10 @@ var core_exports = {};
|
|
|
17
17
|
module.exports = __toCommonJS(core_exports);
|
|
18
18
|
__reExport(core_exports, require("./web-search"), module.exports);
|
|
19
19
|
__reExport(core_exports, require("./call-ai"), module.exports);
|
|
20
|
+
__reExport(core_exports, require("./slack"), module.exports);
|
|
20
21
|
// Annotate the CommonJS export names for ESM import in node:
|
|
21
22
|
0 && (module.exports = {
|
|
22
23
|
...require("./web-search"),
|
|
23
|
-
...require("./call-ai")
|
|
24
|
+
...require("./call-ai"),
|
|
25
|
+
...require("./slack")
|
|
24
26
|
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './send-slack-message.tool';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __copyProps = (to, from, except, desc) => {
|
|
7
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
+
for (let key of __getOwnPropNames(from))
|
|
9
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
+
}
|
|
12
|
+
return to;
|
|
13
|
+
};
|
|
14
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
15
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
|
+
var slack_exports = {};
|
|
17
|
+
module.exports = __toCommonJS(slack_exports);
|
|
18
|
+
__reExport(slack_exports, require("./send-slack-message.tool"), module.exports);
|
|
19
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
20
|
+
0 && (module.exports = {
|
|
21
|
+
...require("./send-slack-message.tool")
|
|
22
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./send-slack-message.tool";
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var send_slack_message_tool_exports = {};
|
|
20
|
+
__export(send_slack_message_tool_exports, {
|
|
21
|
+
sendSlackMessageTool: () => sendSlackMessageTool
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(send_slack_message_tool_exports);
|
|
24
|
+
var import_tool = require("../../tool");
|
|
25
|
+
var import_slack_client = require("../../../clients/slack/slack-client.js");
|
|
26
|
+
const sendSlackMessageTool = new import_tool.Tool({
|
|
27
|
+
name: "send_slack_message",
|
|
28
|
+
description: "Send a message to a Slack channel",
|
|
29
|
+
destructive: false,
|
|
30
|
+
parameters: {
|
|
31
|
+
type: "object",
|
|
32
|
+
properties: {
|
|
33
|
+
channel: {
|
|
34
|
+
type: "string",
|
|
35
|
+
description: "channel id (C0123456789) or name (#general) to send the message to"
|
|
36
|
+
},
|
|
37
|
+
text: {
|
|
38
|
+
type: "string",
|
|
39
|
+
description: 'content of the message. Use Slack mrkdwn when it helps readability: *bold*, _italic_, ~strike~, `code`, <https://url|label> for links and "- " for lists. Do not use standard Markdown (no **bold**, no # headings, no [label](url))'
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
required: ["channel", "text"]
|
|
43
|
+
},
|
|
44
|
+
handler: async (params) => {
|
|
45
|
+
if (!params) throw new Error("[send_slack_message] params is required");
|
|
46
|
+
const { channel, text } = params;
|
|
47
|
+
const sent = await new import_slack_client.SlackClient().sendMessage({ channel, text });
|
|
48
|
+
return { data: sent };
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
52
|
+
0 && (module.exports = {
|
|
53
|
+
sendSlackMessageTool
|
|
54
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import "../../../chunk-CF3WOMB3.mjs";
|
|
2
|
+
import { Tool } from "../../tool";
|
|
3
|
+
import { SlackClient } from "../../../clients/slack/slack-client.js";
|
|
4
|
+
const sendSlackMessageTool = new Tool({
|
|
5
|
+
name: "send_slack_message",
|
|
6
|
+
description: "Send a message to a Slack channel",
|
|
7
|
+
destructive: false,
|
|
8
|
+
parameters: {
|
|
9
|
+
type: "object",
|
|
10
|
+
properties: {
|
|
11
|
+
channel: {
|
|
12
|
+
type: "string",
|
|
13
|
+
description: "channel id (C0123456789) or name (#general) to send the message to"
|
|
14
|
+
},
|
|
15
|
+
text: {
|
|
16
|
+
type: "string",
|
|
17
|
+
description: 'content of the message. Use Slack mrkdwn when it helps readability: *bold*, _italic_, ~strike~, `code`, <https://url|label> for links and "- " for lists. Do not use standard Markdown (no **bold**, no # headings, no [label](url))'
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
required: ["channel", "text"]
|
|
21
|
+
},
|
|
22
|
+
handler: async (params) => {
|
|
23
|
+
if (!params) throw new Error("[send_slack_message] params is required");
|
|
24
|
+
const { channel, text } = params;
|
|
25
|
+
const sent = await new SlackClient().sendMessage({ channel, text });
|
|
26
|
+
return { data: sent };
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
export {
|
|
30
|
+
sendSlackMessageTool
|
|
31
|
+
};
|
package/dist/tools/tool.d.ts
CHANGED
package/dist/tools/tool.js
CHANGED
|
@@ -122,7 +122,7 @@ class Tool {
|
|
|
122
122
|
parameters: mcpTool.inputSchema,
|
|
123
123
|
origin: "mcp",
|
|
124
124
|
server: opts.namespace,
|
|
125
|
-
notice: externalToolNotice(opts.namespace),
|
|
125
|
+
notice: opts.internal ? void 0 : externalToolNotice(opts.namespace),
|
|
126
126
|
handler: async (params = {}) => {
|
|
127
127
|
const { currentUser, sessionId, answerId, ...args } = params;
|
|
128
128
|
const timeoutMs = (0, import_number_setting.numberSetting)("MCP_TOOL_TIMEOUT_MS", DEFAULT_MCP_TOOL_TIMEOUT_MS);
|
package/dist/tools/tool.mjs
CHANGED
|
@@ -99,7 +99,7 @@ class Tool {
|
|
|
99
99
|
parameters: mcpTool.inputSchema,
|
|
100
100
|
origin: "mcp",
|
|
101
101
|
server: opts.namespace,
|
|
102
|
-
notice: externalToolNotice(opts.namespace),
|
|
102
|
+
notice: opts.internal ? void 0 : externalToolNotice(opts.namespace),
|
|
103
103
|
handler: async (params = {}) => {
|
|
104
104
|
const { currentUser, sessionId, answerId, ...args } = params;
|
|
105
105
|
const timeoutMs = numberSetting("MCP_TOOL_TIMEOUT_MS", DEFAULT_MCP_TOOL_TIMEOUT_MS);
|
package/docs/agent.md
CHANGED
|
@@ -34,6 +34,7 @@ const agent = new Agent({
|
|
|
34
34
|
| `maxInputLength` | no | `100000` | Longest message accepted, in characters. Longer messages are blocked by a built-in guard. |
|
|
35
35
|
| `maxIterations` | no | `50` | Hard limit of loop iterations in one run. When reached, the run fails with `AGENT_MAX_ITERATIONS_REACHED`. |
|
|
36
36
|
| `fallbackModel` | no | none | `{ provider, model }` used when neither the run, the chat nor the user chose a model. See [configuration](configuration.md#which-model-a-chat-uses). |
|
|
37
|
+
| `internalMcps` | no | none | MCP servers of your own solution that the user never registers. Also added with `agent.addInternalMcp(mcp)`. See [MCP servers](mcp-servers.md#internal-mcp-servers). |
|
|
37
38
|
| `strictMode` | no | `false` | When `true`, the user is always asked before the agent uses an MCP server whose tools changed after being approved. See [MCP servers](mcp-servers.md#how-the-agent-uses-the-servers). |
|
|
38
39
|
|
|
39
40
|
An `Agent` instance holds the state of the run it is executing, so run one conversation at a time per instance and create another instance for concurrent runs.
|
|
@@ -70,6 +71,8 @@ Omit `chatId` to start a brand-new chat. Pass an existing `chatId` to continue a
|
|
|
70
71
|
|
|
71
72
|
`currentSession` is optional. It carries device, location and locale, which skills use to answer in the right time zone and language.
|
|
72
73
|
|
|
74
|
+
`mcpTokens` is optional. It gives the token of the user to each [internal MCP server](mcp-servers.md#internal-mcp-servers), by name. It is never saved. `serviceToken` is the token that the runner of [agentic jobs](agentic-jobs.md#internal-mcp-servers-in-a-job) passes when there is no session of the user. You do not need it unless you write your own scheduler.
|
|
75
|
+
|
|
73
76
|
## Autonomous mode
|
|
74
77
|
|
|
75
78
|
An autonomous run is one where nobody is in the chat while the agent works, for example a scheduled task. Pass the mode in the run:
|
package/docs/agentic-jobs.md
CHANGED
|
@@ -172,6 +172,16 @@ A new `Agent` is created for every run, so the options are the same but nothing
|
|
|
172
172
|
- It gives the agent the timezone of the job, so the local time reaches the prompts.
|
|
173
173
|
- Guards of the agent apply to the instructions. If one blocks them, the run is `failed`.
|
|
174
174
|
|
|
175
|
+
### Internal MCP servers in a job
|
|
176
|
+
|
|
177
|
+
A job runs without the session of its owner, so there is no token of theirs to send to your [internal MCP servers](mcp-servers.md#internal-mcp-servers). For jobs, the runner uses one token for the whole deployment, taken from `INTERNAL_MCP_TOKEN`. It replaces `{{token}}` in the headers of every internal server, and the runner also sends the id of the owner of the job in the header `X-User-Id`, so your MCP server knows on whose behalf it acts.
|
|
178
|
+
|
|
179
|
+
- Your MCP server must accept `X-User-Id` only together with this service token. Never trust it on a request that carries the token of a user.
|
|
180
|
+
- The header is added only in jobs and only to internal servers that use `{{token}}`. It replaces any `X-User-Id` you configured. It is never sent to the servers added by the user.
|
|
181
|
+
- Without `INTERNAL_MCP_TOKEN`, the internal servers that need a token are unavailable in the jobs, and the run continues without them.
|
|
182
|
+
- The value is read with the secret manager, so it can be encrypted with the `ENC:` prefix.
|
|
183
|
+
- One variable serves all the internal servers. If two of them need different credentials, that is not supported yet.
|
|
184
|
+
|
|
175
185
|
### Running by hand
|
|
176
186
|
|
|
177
187
|
```typescript
|
package/docs/configuration.md
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
| `OPENAI_API_KEY`, `GEMINI_API_KEY` | for those providers | API keys of the other providers you choose per chat. |
|
|
12
12
|
| `JWT_SECRET` | for `login` | Secret that signs the tokens. See [authentication](authentication.md). |
|
|
13
13
|
| `SERPER_API_KEY` | for `webSearchTool` | See [tools](tools.md#built-in-tools). |
|
|
14
|
+
| `SLACK_BOT_TOKEN` | for `sendSlackMessageTool` | See [tools](tools.md#built-in-tools). |
|
|
15
|
+
| `INTERNAL_MCP_TOKEN` | for internal MCP servers in agentic jobs | Token sent to the internal MCP servers when a job runs without the session of its owner. See [agentic jobs](agentic-jobs.md#internal-mcp-servers-in-a-job). |
|
|
14
16
|
| `AGENTIC_JOBS_POLL_INTERVAL_MS` | no | How often the runner of [agentic jobs](agentic-jobs.md) checks what is due, in milliseconds. Defaults to `60000`. |
|
|
15
17
|
| `AGENTIC_JOBS_LEASE_MS` | no | How long a job stays locked while it runs, in milliseconds. Defaults to `600000`. |
|
|
16
18
|
| `LLM_FALLBACK_PROVIDER`, `LLM_FALLBACK_MODEL` | no | The model to use when nothing else chooses one, for the whole deployment. Set both or neither. See [Which model a chat uses](#which-model-a-chat-uses). |
|
package/docs/llms.txt
CHANGED
|
@@ -25,7 +25,7 @@ Start with the integration guide, then read only the pages you need. All pages a
|
|
|
25
25
|
|
|
26
26
|
## Connect and schedule
|
|
27
27
|
|
|
28
|
-
- [MCP servers](mcp-servers.md): registering servers, the trust flow, approving and blocking
|
|
28
|
+
- [MCP servers](mcp-servers.md): registering servers, the trust flow, approving and blocking, internal servers of your own
|
|
29
29
|
- [Agentic jobs](agentic-jobs.md): scheduled agent runs, recurrence, history and the runner
|
|
30
30
|
|
|
31
31
|
## Users and cost
|
package/docs/mcp-servers.md
CHANGED
|
@@ -143,6 +143,44 @@ A server that cannot be reached after a few retries is reported as unavailable f
|
|
|
143
143
|
|
|
144
144
|
Connections are closed at the end of every turn, including when the turn fails.
|
|
145
145
|
|
|
146
|
+
## Internal MCP servers
|
|
147
|
+
|
|
148
|
+
An internal MCP server belongs to your solution, not to the user. The user never registers it and never sees it: they ask the agent for something, and the agent queries your own MCP server behind the scenes with the token of the user. It is declared in code, once, and it is not stored in the database.
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
const agent = new Agent({
|
|
152
|
+
loop: new AgiLoop(),
|
|
153
|
+
internalMcps: [
|
|
154
|
+
{
|
|
155
|
+
name: 'sofi',
|
|
156
|
+
url: 'https://api.sofi.cash/mcp',
|
|
157
|
+
headers: {
|
|
158
|
+
Authorization: 'Bearer {{token}}',
|
|
159
|
+
'X-App': 'sofi-agent',
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
],
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
agent.addInternalMcp({ name: 'other', url: 'https://other.example.com/mcp' })
|
|
166
|
+
|
|
167
|
+
await agent.run({
|
|
168
|
+
input: { message: 'how much did I spend on food this month?' },
|
|
169
|
+
currentUser,
|
|
170
|
+
mcpTokens: { sofi: sessionToken },
|
|
171
|
+
})
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
- `name` and `url` are required, and the name must be unique among the internal servers. `headers` is optional.
|
|
175
|
+
- `{{token}}` in a header value is replaced with `mcpTokens[name]` of the run. A header without the placeholder is sent as written, so the other headers are plain strings. If no header uses `{{token}}`, the server needs no token.
|
|
176
|
+
- The token lives only in memory during the run. Do not put it in `options`, which is saved in the chat. It is masked in the connection errors the agent logs.
|
|
177
|
+
- It is trusted: no approval is asked, the manifest is not reviewed or stored, and its tools are not marked as written by a third party. The tools still follow the rules of the tool pipeline, so a tool with `destructiveHint` asks the user before it runs.
|
|
178
|
+
- If the token of a server is missing for a run, or it cannot be reached, the agent leaves it out for that run, writes a trace and a log, and tells the model that the source is unavailable, so it says it could not access that information. The run does not fail. It does not tell the user the details, only that the source was not reachable.
|
|
179
|
+
- If a server of the user has the same name as an internal one, the one of the user is ignored for that run, so nobody can impersonate an internal server.
|
|
180
|
+
- The tools are named `<name>__<tool>`, like any other MCP tool.
|
|
181
|
+
|
|
182
|
+
In an agentic job there is no session of the user, so there is no token of theirs. See [agentic jobs](agentic-jobs.md#internal-mcp-servers-in-a-job).
|
|
183
|
+
|
|
146
184
|
## Tools of MCP servers
|
|
147
185
|
|
|
148
186
|
Their names are prefixed with the server name, and they are marked as external so the model treats their descriptions as data. A tool is destructive when the server marks it with `destructiveHint`. A tool without that annotation is not treated as destructive, so rely on the server's approval and on your own review of what the server exposes.
|
package/docs/tools.md
CHANGED
|
@@ -75,6 +75,18 @@ agent.addTool(webSearchTool)
|
|
|
75
75
|
|
|
76
76
|
Requires a [Serper](https://serper.dev) API key. Set `SERPER_API_KEY` in your `.env`.
|
|
77
77
|
|
|
78
|
+
### `sendSlackMessageTool`
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { sendSlackMessageTool } from 'openloops/tools'
|
|
82
|
+
|
|
83
|
+
agent.addTool(sendSlackMessageTool)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Sends a message to a Slack channel. The model gives a `channel` (an id such as `C0123456789`, or a name such as `#general`) and the `text`. It returns the `channel` id and the `ts` of the message in `data`.
|
|
87
|
+
|
|
88
|
+
Requires a Slack app with the `chat:write` scope, installed in your workspace and invited to the channel. Set its bot token in `SLACK_BOT_TOKEN`. The token belongs to the deployment, so every agent can write to any channel where the bot is.
|
|
89
|
+
|
|
78
90
|
### `callAiTool`
|
|
79
91
|
|
|
80
92
|
An LLM-backed tool for ad-hoc analysis, summarization, extraction or transformation. It is useful as a fallback when no other tool fits a step.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Agent } from 'openloops/core'
|
|
2
|
+
import { Logger } from 'openloops/common'
|
|
3
|
+
import { CurrentUser } from 'openloops/base'
|
|
4
|
+
import { AgiLoop } from 'openloops/loops'
|
|
5
|
+
|
|
6
|
+
async function runAgentWithInternalMcp (sessionToken: string) {
|
|
7
|
+
const logger = new Logger()
|
|
8
|
+
const currentUser = await CurrentUser.asyncFromDB('6ab56894eb20887d1ef7942c')
|
|
9
|
+
|
|
10
|
+
if (!currentUser) throw new Error('[Demo] current user is not defined')
|
|
11
|
+
|
|
12
|
+
const agent = new Agent({
|
|
13
|
+
loop: new AgiLoop(),
|
|
14
|
+
internalMcps: [
|
|
15
|
+
{
|
|
16
|
+
name: 'sofi',
|
|
17
|
+
url: 'https://api.sofi.cash/mcp',
|
|
18
|
+
headers: { Authorization: 'Bearer {{token}}' },
|
|
19
|
+
},
|
|
20
|
+
],
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
const result = await agent.run({
|
|
25
|
+
input: {
|
|
26
|
+
message: 'how much did I spend on food this month?',
|
|
27
|
+
},
|
|
28
|
+
currentUser,
|
|
29
|
+
mcpTokens: { sofi: sessionToken },
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
logger.debug(result, '[Demo] Result')
|
|
33
|
+
} catch (error: any) {
|
|
34
|
+
logger.error(error, '[Demo] Error')
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
runAgentWithInternalMcp('the-token-of-the-session-of-the-user')
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Agent } from 'openloops/core'
|
|
2
|
+
import { Logger } from 'openloops/common'
|
|
3
|
+
import { CurrentUser } from 'openloops/base'
|
|
4
|
+
import { AgiLoop } from 'openloops/loops'
|
|
5
|
+
import { webSearchTool, sendSlackMessageTool } from 'openloops/tools'
|
|
6
|
+
|
|
7
|
+
async function runAgentWithSlack () {
|
|
8
|
+
const logger = new Logger()
|
|
9
|
+
const currentUser = await CurrentUser.asyncFromDB('6ab56894eb20887d1ef7942c')
|
|
10
|
+
|
|
11
|
+
if (!currentUser) throw new Error('[Demo] current user is not defined')
|
|
12
|
+
|
|
13
|
+
const loop = new AgiLoop()
|
|
14
|
+
const agent = new Agent({ loop })
|
|
15
|
+
agent.addTool(webSearchTool) // requires a serper api key (add SERPER_API_KEY to your .env file)
|
|
16
|
+
agent.addTool(sendSlackMessageTool) // requires a slack bot token (add SLACK_BOT_TOKEN to your .env file) and the bot invited to the channel
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
const result = await agent.run({
|
|
20
|
+
input: {
|
|
21
|
+
message: 'search the price of the bitcoin and send it to the #general channel on slack',
|
|
22
|
+
},
|
|
23
|
+
currentUser,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
logger.debug(result, '[Demo] Result')
|
|
27
|
+
} catch (error: any) {
|
|
28
|
+
logger.error(error, '[Demo] Error')
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
runAgentWithSlack()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openloops",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"description": "Open source harness for AI agents: a TypeScript runtime with persistence, tools, MCP trust, approvals and autonomous jobs, where the loop is pluggable",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Jose Barcos",
|