emailengine-app 2.79.1 → 2.79.2
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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +40 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +95 -18
- package/lib/api-routes/account-routes.js +13 -1
- package/lib/api-routes/index.js +12 -0
- package/lib/api-routes/mailbox-routes.js +6 -0
- package/lib/api-routes/mcp-oauth-routes.js +259 -0
- package/lib/api-routes/mcp-routes.js +172 -0
- package/lib/api-routes/message-routes.js +125 -4
- package/lib/api-routes/outbox-routes.js +7 -0
- package/lib/api-routes/permission-map.js +97 -1
- package/lib/api-routes/route-helpers.js +16 -4
- package/lib/api-routes/route-metadata.js +24 -4
- package/lib/api-routes/submit-routes.js +41 -0
- package/lib/api-routes/template-routes.js +7 -0
- package/lib/api-routes/token-routes.js +4 -2
- package/lib/consts.js +30 -1
- package/lib/email-client/base-client.js +102 -117
- package/lib/email-client/gmail-client.js +87 -22
- package/lib/email-client/imap/mailbox.js +140 -66
- package/lib/email-client/outlook-client.js +17 -14
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/lua/s-list-accounts.lua +5 -2
- package/lib/mcp/index.js +29 -0
- package/lib/mcp/inject.js +70 -0
- package/lib/mcp/json-schema.js +120 -0
- package/lib/mcp/listen.js +171 -0
- package/lib/mcp/oauth.js +324 -0
- package/lib/mcp/protocol.js +489 -0
- package/lib/mcp/resources.js +139 -0
- package/lib/mcp/tools.js +655 -0
- package/lib/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +24 -3
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +34 -5
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +43 -1
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +54 -5
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/route-helpers.js +116 -1
- package/lib/utils/network.js +9 -1
- package/lib/web-safe-html.js +61 -0
- package/lib/webhooks.js +3 -8
- package/package.json +9 -8
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +98 -0
- package/static/emailengine.ico +0 -0
- package/static/js/ui.js +465 -1
- package/static/licenses.html +42 -22
- package/translations/messages.pot +57 -57
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- package/views/partials/head_assets.hbs +3 -3
- package/views/partials/mcp_access_levels.hbs +13 -0
- package/views/partials/mcp_account_limit.hbs +14 -0
- package/views/partials/mcp_tool_count.hbs +19 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/account-picker.hbs +59 -0
- package/views/partials/ui/code-block.hbs +26 -0
- package/views/partials/ui/menu-item.hbs +5 -0
- package/views/partials/ui/radio.hbs +41 -0
- package/views/partials/ui/tab.hbs +15 -10
- package/views/partials/ui/tabs.hbs +8 -5
- package/views/templates/template.hbs +4 -3
- package/views/tokens/index.hbs +8 -2
- package/views/tokens/new.hbs +514 -243
- package/winconf.js +148 -48
- package/workers/api.js +198 -48
package/lib/mcp/tools.js
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The MCP tool registry and executor.
|
|
4
|
+
//
|
|
5
|
+
// Tools are not defined here. A route opts in by carrying a `plugins.mcp` block
|
|
6
|
+
// ({ name, title, description, keep?/omit?, force?, bounds?, binary?, resourceUriTemplate? }), and
|
|
7
|
+
// this module derives everything else from what
|
|
8
|
+
// the route already declares: the input schema from its joi validation schemas, the behavior
|
|
9
|
+
// annotations from routeGrant() - the same source /swagger.json publishes as x-ee-action and
|
|
10
|
+
// x-ee-group - and the dispatch target from its method and path. There is deliberately no second
|
|
11
|
+
// description of any endpoint: a tool cannot disagree with the route it wraps.
|
|
12
|
+
//
|
|
13
|
+
// Tool calls are dispatched with server.inject(), so an MCP call IS an API request: the api-token
|
|
14
|
+
// strategy re-runs against the caller's own credential, and scope checks, token permissions,
|
|
15
|
+
// account binding, IP restrictions, rate limits and the token audit log all apply exactly as they
|
|
16
|
+
// do over REST. This module never touches Redis and never bypasses a handler.
|
|
17
|
+
|
|
18
|
+
const { routeGrant, ACTION } = require('../api-routes/permission-map');
|
|
19
|
+
const tokenPermissions = require('../token-permissions');
|
|
20
|
+
const { mcpOptions } = require('../api-routes/route-metadata');
|
|
21
|
+
const { joiToJsonSchema } = require('./json-schema');
|
|
22
|
+
const { apiInject } = require('./inject');
|
|
23
|
+
|
|
24
|
+
// Serialized tool results larger than this are truncated. Message text is attacker-sized input
|
|
25
|
+
// (a single mail can carry megabytes of text), and an oversized tool result degrades or breaks
|
|
26
|
+
// the calling agent, so the cap errs low. The truncation is announced in the result text.
|
|
27
|
+
//
|
|
28
|
+
// Read as tokens rather than as bytes: this is roughly 32k of them, which is already a large
|
|
29
|
+
// share of a context window to spend on one call, and it is a ceiling rather than a target -
|
|
30
|
+
// every tool that can return a lot keeps its own, smaller budget (the forced maxBytes on the two
|
|
31
|
+
// body tools, the `bounds` below on the listings), so a truncated result means something went
|
|
32
|
+
// wrong rather than something got big.
|
|
33
|
+
const MAX_TOOL_RESULT_BYTES = 128 * 1024;
|
|
34
|
+
|
|
35
|
+
// Binary payloads (attachments) above this size are refused with a pointer at the REST download
|
|
36
|
+
// endpoint instead of being base64-inlined into the conversation.
|
|
37
|
+
const MAX_TOOL_BINARY_BYTES = 1024 * 1024;
|
|
38
|
+
|
|
39
|
+
const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the full response was ${size} bytes. Narrow the request to see the rest.]`;
|
|
40
|
+
|
|
41
|
+
// Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
|
|
42
|
+
// misspelling is a build failure rather than a knob that quietly does nothing.
|
|
43
|
+
const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint']);
|
|
44
|
+
|
|
45
|
+
// One registry per Hapi server, built on first use and held for the life of the worker - route
|
|
46
|
+
// definitions cannot change while it runs, and the build walks every joi schema of every wrapped
|
|
47
|
+
// route. Keyed weakly so a test server and its registry are released together.
|
|
48
|
+
const registryCache = new WeakMap();
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The memoized tool registry of a running server. Shared by the /mcp endpoint and the admin UI
|
|
52
|
+
* (the MCP config page renders the tool catalog from it), so the two cannot disagree about what
|
|
53
|
+
* is exposed.
|
|
54
|
+
*
|
|
55
|
+
* @param {Object} server - the Hapi server
|
|
56
|
+
* @returns {{tools: Array, byName: Map}}
|
|
57
|
+
*/
|
|
58
|
+
function getToolRegistry(server) {
|
|
59
|
+
if (!registryCache.has(server)) {
|
|
60
|
+
registryCache.set(server, buildToolRegistry(server.table()));
|
|
61
|
+
}
|
|
62
|
+
return registryCache.get(server);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// The converted schema for one source (path params, query, payload)
|
|
66
|
+
function convertSource(schema) {
|
|
67
|
+
const converted = schema ? joiToJsonSchema(schema) : undefined;
|
|
68
|
+
|
|
69
|
+
if (!converted || converted.type !== 'object' || !converted.properties) {
|
|
70
|
+
return { properties: {}, required: [] };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
properties: converted.properties,
|
|
75
|
+
required: converted.required || []
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Derives the MCP tool list from a Hapi route table.
|
|
81
|
+
*
|
|
82
|
+
* @param {Array} routes - server.table()
|
|
83
|
+
* @returns {{tools: Array, byName: Map}} tool definitions in deterministic (name) order, plus the
|
|
84
|
+
* executor's lookup table carrying the dispatch data the wire format does not
|
|
85
|
+
*/
|
|
86
|
+
function buildToolRegistry(routes) {
|
|
87
|
+
const byName = new Map();
|
|
88
|
+
|
|
89
|
+
for (const route of routes) {
|
|
90
|
+
const options = mcpOptions(route);
|
|
91
|
+
if (!options.name) {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (byName.has(options.name)) {
|
|
96
|
+
// Two routes claiming one tool name is a wiring bug, and last-write-wins would pick
|
|
97
|
+
// the tool by iteration order. Same rule as the ROUTE_GROUPS inversion.
|
|
98
|
+
throw new Error(`MCP tool ${options.name} is declared by two routes`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Nothing else checks the shape of a plugins.mcp block, so a misspelled key would be a
|
|
102
|
+
// silent no-op - and every knob here is one that hides or pins something on the
|
|
103
|
+
// agent-facing schema, where a no-op means the opposite of what was declared
|
|
104
|
+
const unknownOptions = Object.keys(options).filter(key => !MCP_OPTION_KEYS.has(key));
|
|
105
|
+
if (unknownOptions.length) {
|
|
106
|
+
throw new Error(`MCP tool ${options.name}: unknown plugins.mcp option${unknownOptions.length > 1 ? 's' : ''}: ${unknownOptions.join(', ')}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const validate = (route.settings && route.settings.validate) || {};
|
|
110
|
+
|
|
111
|
+
// Which arguments the tool offers, expressed either way round. `keep` is the allowlist
|
|
112
|
+
// form and is what the composition tools use: their exposed set is small, the route's is
|
|
113
|
+
// large and grows, and with a deny list a field added to the submit route later would
|
|
114
|
+
// join send_message's schema by default - failing open on the one tool that reaches
|
|
115
|
+
// people outside the mailbox. `omit` stays for the tools that hide two or three knobs
|
|
116
|
+
// out of a stable handful, where an allowlist would be a list of everything.
|
|
117
|
+
if (options.keep && options.omit) {
|
|
118
|
+
throw new Error(`MCP tool ${options.name}: declare either keep or omit, not both`);
|
|
119
|
+
}
|
|
120
|
+
const keep = options.keep ? new Set(options.keep) : null;
|
|
121
|
+
const omit = new Set(options.omit || []);
|
|
122
|
+
|
|
123
|
+
const params = convertSource(validate.params);
|
|
124
|
+
const query = convertSource(validate.query);
|
|
125
|
+
const payload = convertSource(validate.payload);
|
|
126
|
+
|
|
127
|
+
const properties = {};
|
|
128
|
+
const required = [];
|
|
129
|
+
const sources = new Map();
|
|
130
|
+
// Every request argument of the route, hidden ones included. `sources` is what a caller
|
|
131
|
+
// may address; this is what the route actually accepts, and it is what a forced value has
|
|
132
|
+
// to be looked up in - a forced argument is almost always a hidden one.
|
|
133
|
+
const argSources = new Map();
|
|
134
|
+
// The arguments the tool does not offer, and the subset of those the route requires
|
|
135
|
+
const hidden = new Set();
|
|
136
|
+
const hiddenRequired = new Set();
|
|
137
|
+
|
|
138
|
+
for (const [sourceName, source] of [
|
|
139
|
+
['params', params],
|
|
140
|
+
['query', query],
|
|
141
|
+
['payload', payload]
|
|
142
|
+
]) {
|
|
143
|
+
for (const [key, propertySchema] of Object.entries(source.properties)) {
|
|
144
|
+
if (argSources.has(key)) {
|
|
145
|
+
// A path parameter and a payload field sharing a name cannot both be a single
|
|
146
|
+
// tool argument. None of the wrapped routes do this; refuse at build time so
|
|
147
|
+
// the next one cannot silently shadow.
|
|
148
|
+
throw new Error(`MCP tool ${options.name}: argument ${key} is defined by two request sources`);
|
|
149
|
+
}
|
|
150
|
+
argSources.set(key, sourceName);
|
|
151
|
+
if (keep ? !keep.has(key) : omit.has(key)) {
|
|
152
|
+
hidden.add(key);
|
|
153
|
+
if (source.required.includes(key)) {
|
|
154
|
+
// A required argument the tool does not offer has to be supplied by
|
|
155
|
+
// `force`, or every call dies on the same joi 400 with nothing the model
|
|
156
|
+
// can do about it
|
|
157
|
+
hiddenRequired.add(key);
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
sources.set(key, sourceName);
|
|
162
|
+
properties[key] = propertySchema;
|
|
163
|
+
if (source.required.includes(key)) {
|
|
164
|
+
required.push(key);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Both lists are checked against what the route actually accepts. A name that matches no
|
|
170
|
+
// argument is the failure mode this exists to catch: it reads as a decision that was made
|
|
171
|
+
// and is not in force - a still-exposed knob under `omit`, a still-hidden one under
|
|
172
|
+
// `keep`.
|
|
173
|
+
for (const [label, declared] of [
|
|
174
|
+
['kept', options.keep || []],
|
|
175
|
+
['omitted', options.omit || []]
|
|
176
|
+
]) {
|
|
177
|
+
for (const key of declared) {
|
|
178
|
+
if (!argSources.has(key)) {
|
|
179
|
+
throw new Error(`MCP tool ${options.name}: ${label} argument ${key} is not an argument of ${route.method} ${route.path}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Values the MCP layer pins on every call, so a tool has one behavior rather than a matrix
|
|
185
|
+
// of them. A forced value is sent with the injected request but is not a tool argument: the
|
|
186
|
+
// point is that the calling model does not get to choose. The lookup is against every
|
|
187
|
+
// argument of the route rather than against the tool's own, since a hidden key has left
|
|
188
|
+
// the latter - which is also why `force` on a still-offered argument is refused. That pair
|
|
189
|
+
// is the whole mechanism, and declaring one half of it would advertise an argument whose
|
|
190
|
+
// value is then thrown away, which reads to the model as a control it does not have.
|
|
191
|
+
const force = Object.entries(options.force || {});
|
|
192
|
+
const forcedValues = {};
|
|
193
|
+
// The routing table the injected request is built from: the tool's own arguments plus the
|
|
194
|
+
// forced ones, which are not tool arguments and so are absent from `sources`. Only when
|
|
195
|
+
// there is something to add - otherwise the tool routes through `sources` itself.
|
|
196
|
+
const forcedSources = force.length ? new Map(sources) : sources;
|
|
197
|
+
|
|
198
|
+
for (const [key, value] of force) {
|
|
199
|
+
const sourceName = argSources.get(key);
|
|
200
|
+
if (!sourceName) {
|
|
201
|
+
throw new Error(`MCP tool ${options.name}: forced argument ${key} is not an argument of ${route.method} ${route.path}`);
|
|
202
|
+
}
|
|
203
|
+
if (!hidden.has(key)) {
|
|
204
|
+
throw new Error(`MCP tool ${options.name}: forced argument ${key} must also be hidden, or the schema offers a choice that is not there`);
|
|
205
|
+
}
|
|
206
|
+
forcedSources.set(key, sourceName);
|
|
207
|
+
forcedValues[key] = value;
|
|
208
|
+
hiddenRequired.delete(key);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (hiddenRequired.size) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
`MCP tool ${options.name}: required argument${hiddenRequired.size > 1 ? 's' : ''} ${[...hiddenRequired].join(', ')} ` +
|
|
214
|
+
`${hiddenRequired.size > 1 ? 'are' : 'is'} hidden but not forced, so every call would fail validation`
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Ceilings the MCP layer lowers on an argument the route keeps offering in full (see
|
|
219
|
+
// MCP_MAX_PAGE_SIZE in lib/consts.js for the case this exists for). The advertised
|
|
220
|
+
// maximum comes down AND the dispatch clamps, so the bound holds for a client that
|
|
221
|
+
// ignores the schema too.
|
|
222
|
+
//
|
|
223
|
+
// Refused at build time unless it actually narrows an exposed numeric argument - a bound
|
|
224
|
+
// that names a hidden key, or one the route has since raised past, is a bound that
|
|
225
|
+
// silently stopped doing anything.
|
|
226
|
+
const bounds = new Map();
|
|
227
|
+
for (const [key, max] of Object.entries(options.bounds || {})) {
|
|
228
|
+
if (!sources.has(key)) {
|
|
229
|
+
throw new Error(`MCP tool ${options.name}: bounded argument ${key} is not an exposed argument of ${route.method} ${route.path}`);
|
|
230
|
+
}
|
|
231
|
+
if (typeof properties[key].maximum !== 'number' || properties[key].maximum <= max) {
|
|
232
|
+
throw new Error(`MCP tool ${options.name}: bound on ${key} does not narrow the schema maximum (${properties[key].maximum})`);
|
|
233
|
+
}
|
|
234
|
+
properties[key] = Object.assign({}, properties[key], { maximum: max });
|
|
235
|
+
bounds.set(key, max);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const grant = routeGrant(route);
|
|
239
|
+
|
|
240
|
+
const annotations = {
|
|
241
|
+
title: options.title,
|
|
242
|
+
readOnlyHint: grant.action === ACTION.READ,
|
|
243
|
+
destructiveHint: grant.action === ACTION.DESTRUCTIVE,
|
|
244
|
+
// Sending mail reaches arbitrary external recipients; everything else stays inside
|
|
245
|
+
// the connected mailboxes
|
|
246
|
+
openWorldHint: grant.action === ACTION.SEND
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const inputSchema = {
|
|
250
|
+
type: 'object',
|
|
251
|
+
properties,
|
|
252
|
+
additionalProperties: false
|
|
253
|
+
};
|
|
254
|
+
if (required.length) {
|
|
255
|
+
inputSchema.required = required;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
byName.set(options.name, {
|
|
259
|
+
definition: {
|
|
260
|
+
name: options.name,
|
|
261
|
+
title: options.title,
|
|
262
|
+
description: options.description || (route.settings && route.settings.description),
|
|
263
|
+
inputSchema,
|
|
264
|
+
annotations
|
|
265
|
+
},
|
|
266
|
+
method: route.method,
|
|
267
|
+
path: route.path,
|
|
268
|
+
sources,
|
|
269
|
+
forcedSources,
|
|
270
|
+
forcedValues,
|
|
271
|
+
bounds,
|
|
272
|
+
// The operation this tool resolves to, for consumers that answer per-credential
|
|
273
|
+
// questions about the catalog: tools/list uses it to show a permission-narrowed
|
|
274
|
+
// token only the tools its record can actually call
|
|
275
|
+
grant,
|
|
276
|
+
binary: !!options.binary,
|
|
277
|
+
resourceUriTemplate: options.resourceUriTemplate
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const tools = [...byName.values()].map(entry => entry.definition).sort((a, b) => a.name.localeCompare(b.name, 'en'));
|
|
282
|
+
|
|
283
|
+
return { tools, byName };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The effective arguments and their request sources for one call.
|
|
288
|
+
*
|
|
289
|
+
* Three inputs are folded together here: what the caller sent, the values the tool forces (which
|
|
290
|
+
* the caller cannot have sent - the builder refuses a forced argument that is still exposed), and
|
|
291
|
+
* the account a bound credential is pinned to.
|
|
292
|
+
*
|
|
293
|
+
* The binding is a default rather than an override. A bound credential is advertised tools that
|
|
294
|
+
* take no `account` argument at all (see toolDefinitionFor), so the argument is normally absent
|
|
295
|
+
* and filled in here - but a client working from a stale catalog still sends one, and letting it
|
|
296
|
+
* through unchanged keeps the mismatch a 403 from the inner request rather than a call that
|
|
297
|
+
* quietly acts on a different mailbox than the one asked for.
|
|
298
|
+
*
|
|
299
|
+
* @param {Object} tool - registry entry
|
|
300
|
+
* @param {Object} args - arguments as sent by the client
|
|
301
|
+
* @param {String} [boundAccount] - the account this credential is pinned to, if any
|
|
302
|
+
* @returns {{args: Object, sources: Map}}
|
|
303
|
+
*/
|
|
304
|
+
function effectiveArguments(tool, args, boundAccount) {
|
|
305
|
+
const effective = Object.assign({}, args, tool.forcedValues);
|
|
306
|
+
|
|
307
|
+
if (boundAccount && tool.sources.has('account') && (effective.account === undefined || effective.account === null || effective.account === '')) {
|
|
308
|
+
effective.account = boundAccount;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Clamped rather than refused: the value came out of a model reading the advertised maximum,
|
|
312
|
+
// and answering a too-large page with an error teaches it nothing the smaller page does not.
|
|
313
|
+
// Number() because the wire is not obliged to send the JSON type the schema names.
|
|
314
|
+
for (const [key, max] of tool.bounds) {
|
|
315
|
+
const value = Number(effective[key]);
|
|
316
|
+
if (Number.isFinite(value) && value > max) {
|
|
317
|
+
effective[key] = max;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return { args: effective, sources: tool.forcedSources };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Fills a Hapi path template ('/v1/account/{account}/message/{message}') from tool arguments.
|
|
325
|
+
function buildPath(template, args, sources) {
|
|
326
|
+
return template.replace(/\{([^}]+)\}/g, (match, name) => {
|
|
327
|
+
// A missing path parameter can only mean the argument was optional in the schema and the
|
|
328
|
+
// caller left it out; the joi 400 from the injected request names it either way, but the
|
|
329
|
+
// URL must not be built with the literal placeholder in it.
|
|
330
|
+
if (!sources.has(name) || args[name] === undefined || args[name] === null) {
|
|
331
|
+
return '';
|
|
332
|
+
}
|
|
333
|
+
return encodeURIComponent(String(args[name]));
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function buildQuery(args, sources) {
|
|
338
|
+
const query = new URLSearchParams();
|
|
339
|
+
|
|
340
|
+
for (const [key, sourceName] of sources) {
|
|
341
|
+
if (sourceName !== 'query' || args[key] === undefined || args[key] === null) {
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
for (const value of [].concat(args[key])) {
|
|
345
|
+
query.append(key, String(value));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const rendered = query.toString();
|
|
350
|
+
return rendered ? `?${rendered}` : '';
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function textResult(text, { isError = false } = {}) {
|
|
354
|
+
const result = { content: [{ type: 'text', text }] };
|
|
355
|
+
if (isError) {
|
|
356
|
+
result.isError = true;
|
|
357
|
+
}
|
|
358
|
+
return result;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Cuts a string to a UTF-8 byte budget.
|
|
363
|
+
*
|
|
364
|
+
* String.slice() counts UTF-16 code units, so slicing to the byte cap left a result up to three
|
|
365
|
+
* times over it - a mailbox of CJK or Cyrillic text sailed through the cap while carrying a
|
|
366
|
+
* notice claiming it had been truncated. Cutting the encoded bytes instead, then walking back off
|
|
367
|
+
* any trailing continuation byte, keeps the budget honest and never emits a split code point.
|
|
368
|
+
*/
|
|
369
|
+
function truncateToBytes(text, maxBytes) {
|
|
370
|
+
const buf = Buffer.from(text, 'utf8');
|
|
371
|
+
if (buf.length <= maxBytes) {
|
|
372
|
+
return text;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
let end = maxBytes;
|
|
376
|
+
// 0b10xxxxxx marks a continuation byte, so back up until `end` sits on a lead byte
|
|
377
|
+
while (end > 0 && (buf[end] & 0xc0) === 0x80) {
|
|
378
|
+
end--;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return buf.subarray(0, end).toString('utf8');
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function jsonResult(value) {
|
|
385
|
+
// Compact on purpose: an indent is pure padding to a model, it inflates every response by a
|
|
386
|
+
// double-digit percentage, and it counts against the size cap below
|
|
387
|
+
let text = JSON.stringify(value);
|
|
388
|
+
let structuredContent = value;
|
|
389
|
+
|
|
390
|
+
const size = Buffer.byteLength(text);
|
|
391
|
+
if (size > MAX_TOOL_RESULT_BYTES) {
|
|
392
|
+
text = truncateToBytes(text, MAX_TOOL_RESULT_BYTES) + TRUNCATION_NOTICE(size);
|
|
393
|
+
// A structuredContent that repeats the oversized value would defeat the cap
|
|
394
|
+
structuredContent = undefined;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const result = { content: [{ type: 'text', text }] };
|
|
398
|
+
if (structuredContent !== undefined && structuredContent !== null && typeof structuredContent === 'object') {
|
|
399
|
+
result.structuredContent = structuredContent;
|
|
400
|
+
}
|
|
401
|
+
return result;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Executes one tool call by injecting the equivalent API request.
|
|
406
|
+
*
|
|
407
|
+
* @param {Object} opts
|
|
408
|
+
* @param {Object} opts.server - the Hapi server (for inject)
|
|
409
|
+
* @param {Object} opts.tool - registry entry from buildToolRegistry().byName
|
|
410
|
+
* @param {Object} opts.args - tool arguments as sent by the client
|
|
411
|
+
* @param {Object} opts.request - the outer /mcp request (credential, client IP, timeout header)
|
|
412
|
+
* @returns {Object} an MCP tool result ({ content, structuredContent?, isError? })
|
|
413
|
+
*/
|
|
414
|
+
async function callTool({ server, tool, args, request }) {
|
|
415
|
+
args = args || {};
|
|
416
|
+
|
|
417
|
+
if (typeof args !== 'object' || Array.isArray(args)) {
|
|
418
|
+
return textResult('Tool arguments must be an object', { isError: true });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const unknown = Object.keys(args).filter(key => !tool.sources.has(key));
|
|
422
|
+
if (unknown.length) {
|
|
423
|
+
return textResult(`Unknown tool argument${unknown.length > 1 ? 's' : ''}: ${unknown.join(', ')}`, { isError: true });
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const boundAccount = request.app && request.app.mcpBoundAccount;
|
|
427
|
+
const effective = effectiveArguments(tool, args, boundAccount);
|
|
428
|
+
|
|
429
|
+
// Required arguments are checked here rather than left to the injected request. A missing
|
|
430
|
+
// path parameter does not reach joi at all: it renders as an empty path segment, and Hapi
|
|
431
|
+
// answers the resulting `/v1/account//message/x` with a bare 404 that names neither the tool
|
|
432
|
+
// nor the argument, which an agent can only respond to by retrying the same call.
|
|
433
|
+
//
|
|
434
|
+
// Checked over the effective arguments, so the account a bound credential never had to send
|
|
435
|
+
// does not read as one it forgot.
|
|
436
|
+
const missing = (tool.definition.inputSchema.required || []).filter(key => effective.args[key] === undefined || effective.args[key] === null);
|
|
437
|
+
if (missing.length) {
|
|
438
|
+
return textResult(`Missing required tool argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`, { isError: true });
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const payload = {};
|
|
442
|
+
let hasPayload = false;
|
|
443
|
+
for (const [key, sourceName] of effective.sources) {
|
|
444
|
+
if (sourceName === 'payload' && effective.args[key] !== undefined) {
|
|
445
|
+
payload[key] = effective.args[key];
|
|
446
|
+
hasPayload = true;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const res = await apiInject({
|
|
451
|
+
server,
|
|
452
|
+
request,
|
|
453
|
+
method: tool.method,
|
|
454
|
+
url: buildPath(tool.path, effective.args, effective.sources) + buildQuery(effective.args, effective.sources),
|
|
455
|
+
payload: hasPayload ? payload : undefined
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
if (res.statusCode >= 400) {
|
|
459
|
+
// The API's own error payload (a Boom body plus fields like requiredPermission) is the
|
|
460
|
+
// actionable feedback; tool-execution errors are results, not protocol errors
|
|
461
|
+
let body = res.result;
|
|
462
|
+
if (Buffer.isBuffer(body)) {
|
|
463
|
+
body = body.toString();
|
|
464
|
+
}
|
|
465
|
+
return textResult(typeof body === 'string' ? body : JSON.stringify(body), { isError: true });
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
if (tool.binary) {
|
|
469
|
+
const data = res.rawPayload || Buffer.alloc(0);
|
|
470
|
+
|
|
471
|
+
if (data.length > MAX_TOOL_BINARY_BYTES) {
|
|
472
|
+
return textResult(
|
|
473
|
+
`The file is ${data.length} bytes, which is larger than the ${MAX_TOOL_BINARY_BYTES} byte limit for inline tool results. ` +
|
|
474
|
+
`Download it over the REST API instead: GET ${tool.path}`,
|
|
475
|
+
{ isError: true }
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return {
|
|
480
|
+
content: [
|
|
481
|
+
{
|
|
482
|
+
type: 'resource',
|
|
483
|
+
resource: {
|
|
484
|
+
uri: buildResourceUri(tool, effective.args),
|
|
485
|
+
mimeType: res.headers['content-type'] || 'application/octet-stream',
|
|
486
|
+
blob: data.toString('base64')
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
]
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (res.result === null || res.result === undefined) {
|
|
494
|
+
return textResult('OK');
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (typeof res.result === 'string') {
|
|
498
|
+
return textResult(res.result);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
return jsonResult(dropPlaintextTwin(res.result));
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Reduces a message body to the one rendering an MCP caller is given.
|
|
506
|
+
*
|
|
507
|
+
* The web-safe HTML is generated from both MIME parts, so the plaintext part beside it is the same
|
|
508
|
+
* message a second time: double the tokens for a rendering the model has no use for, on the largest
|
|
509
|
+
* results this endpoint returns. Keyed on the `webSafe` marker the API sets rather than on a tool
|
|
510
|
+
* name, so it only ever fires where the HTML really is the generated one.
|
|
511
|
+
*
|
|
512
|
+
* Only `get_message` needs this. The text endpoint's own web-safe mode returns one body already
|
|
513
|
+
* (webSafeTextResponse in lib/web-safe-html.js), which is where that promise belongs - it is the
|
|
514
|
+
* shape of the API response, not something the MCP layer decides.
|
|
515
|
+
*
|
|
516
|
+
* @param {*} result - the API response
|
|
517
|
+
* @returns {*} the same value, with the redundant plaintext removed
|
|
518
|
+
*/
|
|
519
|
+
function dropPlaintextTwin(result) {
|
|
520
|
+
const text = result && result.text;
|
|
521
|
+
if (text && typeof text === 'object' && text.webSafe === true) {
|
|
522
|
+
delete text.plain;
|
|
523
|
+
}
|
|
524
|
+
return result;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// A stable, opaque identifier for binary content, so the client has a URI to attach the blob to.
|
|
528
|
+
// These are not listed by resources/list and not readable by resources/read - the tool result
|
|
529
|
+
// carries the content inline.
|
|
530
|
+
function buildResourceUri(tool, args) {
|
|
531
|
+
const template = tool.resourceUriTemplate || `emailengine://${tool.path.replace(/^\/v1\//, '')}`;
|
|
532
|
+
return template.replace(/\{([^}]+)\}/g, (match, name) => encodeURIComponent(String(args[name] === undefined ? '' : args[name])));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Whether one credential is advertised one tool.
|
|
537
|
+
*
|
|
538
|
+
* The single spelling of what tools/list filters on, so a credential's view of the catalog is
|
|
539
|
+
* decided in one place. Two rules, and a consumer that applies only one of them overstates the
|
|
540
|
+
* catalog: the permission record, and the account binding - a credential bound to one account is
|
|
541
|
+
* never offered the tools that take no account argument, because there is nothing to bind them to.
|
|
542
|
+
*
|
|
543
|
+
* Advertisement only. tools/call dispatches whatever is asked and the injected inner request stays
|
|
544
|
+
* the enforcement, so this is allowed to be a prediction rather than a gate.
|
|
545
|
+
*
|
|
546
|
+
* @param {Object} entry - a registry entry, from getToolRegistry().byName
|
|
547
|
+
* @param {Object} opts
|
|
548
|
+
* @param {Object} opts.tokenData - the token record, as the auth strategy leaves it in artifacts
|
|
549
|
+
* @param {String} [opts.boundAccount] - the account this credential is pinned to, if any
|
|
550
|
+
* @returns {Boolean}
|
|
551
|
+
*/
|
|
552
|
+
function toolVisibleTo(entry, { tokenData, boundAccount }) {
|
|
553
|
+
if (boundAccount && !entry.sources.has('account')) {
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
return tokenPermissions.check({ tokenData, operation: entry.grant }).allowed;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* The tool definition one credential is shown.
|
|
561
|
+
*
|
|
562
|
+
* An account-bound credential reaches exactly one account, and the endpoint knows which - so its
|
|
563
|
+
* tools do not take an `account` argument at all. Leaving it in the schema asks the model for a
|
|
564
|
+
* value it has no way to know (the same credential is refused the account listing), which is a
|
|
565
|
+
* failed call and a round trip of guessing before the agent gets anywhere. The executor fills the
|
|
566
|
+
* binding in on dispatch.
|
|
567
|
+
*
|
|
568
|
+
* The stripped definition is derived once per registry entry and cached on it: the shape does not
|
|
569
|
+
* depend on which account the credential is bound to, only on whether it is bound at all.
|
|
570
|
+
*
|
|
571
|
+
* @param {Object} entry - a registry entry, from getToolRegistry().byName
|
|
572
|
+
* @param {Object} opts
|
|
573
|
+
* @param {String} [opts.boundAccount] - the account this credential is pinned to, if any
|
|
574
|
+
* @returns {Object} the tool definition to advertise
|
|
575
|
+
*/
|
|
576
|
+
function toolDefinitionFor(entry, { boundAccount } = {}) {
|
|
577
|
+
if (!boundAccount || !entry.sources.has('account')) {
|
|
578
|
+
return entry.definition;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (!entry.boundDefinition) {
|
|
582
|
+
const properties = Object.assign({}, entry.definition.inputSchema.properties);
|
|
583
|
+
delete properties.account;
|
|
584
|
+
|
|
585
|
+
const inputSchema = Object.assign({}, entry.definition.inputSchema, { properties });
|
|
586
|
+
const required = (entry.definition.inputSchema.required || []).filter(key => key !== 'account');
|
|
587
|
+
if (required.length) {
|
|
588
|
+
inputSchema.required = required;
|
|
589
|
+
} else {
|
|
590
|
+
delete inputSchema.required;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
entry.boundDefinition = Object.assign({}, entry.definition, { inputSchema });
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
return entry.boundDefinition;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* The catalog one credential is advertised, in tools/list order.
|
|
601
|
+
*
|
|
602
|
+
* The single spelling of per-credential advertisement: which tools are offered (toolVisibleTo) and
|
|
603
|
+
* what each of them looks like to this caller (toolDefinitionFor). The route handler calls this
|
|
604
|
+
* rather than applying the two itself, so the filter and the reshaping cannot come apart.
|
|
605
|
+
*
|
|
606
|
+
* @param {Object} server - the Hapi server
|
|
607
|
+
* @param {Object} opts
|
|
608
|
+
* @param {Object} opts.tokenData - the token record, as the auth strategy leaves it in artifacts
|
|
609
|
+
* @param {String} [opts.boundAccount] - the account this credential is pinned to, if any
|
|
610
|
+
* @returns {Array} tool definitions
|
|
611
|
+
*/
|
|
612
|
+
function listToolsFor(server, { tokenData, boundAccount }) {
|
|
613
|
+
const { tools, byName } = getToolRegistry(server);
|
|
614
|
+
return tools
|
|
615
|
+
.map(tool => byName.get(tool.name))
|
|
616
|
+
.filter(entry => toolVisibleTo(entry, { tokenData, boundAccount }))
|
|
617
|
+
.map(entry => toolDefinitionFor(entry, { boundAccount }));
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* The exposed tools with the operation each one dispatches under, in tools/list order.
|
|
622
|
+
*
|
|
623
|
+
* For consumers that answer per-credential questions about the catalog without dispatching
|
|
624
|
+
* anything - the admin token form counts how many tools a permission record would leave callable,
|
|
625
|
+
* which is what the two permission axes alone cannot tell a reader. Kept here rather than having
|
|
626
|
+
* callers walk `byName`, so the dispatch table stays this module's business.
|
|
627
|
+
*
|
|
628
|
+
* `accountScoped` is what the binding half of toolVisibleTo() reads, carried along because the
|
|
629
|
+
* admin pages have to apply the same two filters in a browser, where neither this module nor the
|
|
630
|
+
* permission checker can be called. test/mcp-tools-test.js asserts that the two-allowlist model
|
|
631
|
+
* those pages use agrees with toolVisibleTo() over the whole catalog, so the prediction cannot
|
|
632
|
+
* drift away from the rule it predicts.
|
|
633
|
+
*
|
|
634
|
+
* @param {Object} server - the Hapi server
|
|
635
|
+
* @returns {Array<{name: String, action: String, group: String, accountScoped: Boolean}>}
|
|
636
|
+
*/
|
|
637
|
+
function toolGrants(server) {
|
|
638
|
+
const { tools, byName } = getToolRegistry(server);
|
|
639
|
+
return tools.map(tool => {
|
|
640
|
+
const entry = byName.get(tool.name);
|
|
641
|
+
return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account') }, entry.grant);
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
module.exports = {
|
|
646
|
+
buildToolRegistry,
|
|
647
|
+
getToolRegistry,
|
|
648
|
+
toolGrants,
|
|
649
|
+
toolVisibleTo,
|
|
650
|
+
toolDefinitionFor,
|
|
651
|
+
listToolsFor,
|
|
652
|
+
callTool,
|
|
653
|
+
MAX_TOOL_RESULT_BYTES,
|
|
654
|
+
MAX_TOOL_BINARY_BYTES
|
|
655
|
+
};
|
package/lib/openapi/index.js
CHANGED
|
@@ -92,4 +92,6 @@ function registerOpenApiRoute(server, options) {
|
|
|
92
92
|
});
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
// serverUrl is shared with the MCP config page, which needs the same "address the client
|
|
96
|
+
// actually used" answer for its connection snippets when no serviceUrl is configured
|
|
97
|
+
module.exports = { registerOpenApiRoute, buildOpenApiDocument, serverUrl, JSON_PATH, NOTES_SEPARATOR, SCHEMA_REF_PREFIX };
|