@terreno/api 57.16.2 → 57.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import {beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import mongoose, {model, Schema} from "mongoose";
|
|
4
|
+
import supertest from "supertest";
|
|
5
|
+
import type TestAgent from "supertest/lib/agent";
|
|
6
|
+
import {modelRouter} from "../api";
|
|
7
|
+
import type {UserModel as UserModelType} from "../auth";
|
|
8
|
+
import {McpServiceToken} from "../models/mcpServiceToken";
|
|
9
|
+
import {Permissions} from "../permissions";
|
|
10
|
+
import {createdUpdatedPlugin} from "../plugins";
|
|
11
|
+
import {createAccess} from "../rbac/access";
|
|
12
|
+
import {terrenoStatements} from "../rbac/statements";
|
|
13
|
+
import {getCurrentRequestContext} from "../requestContext";
|
|
14
|
+
import {TerrenoApp} from "../terrenoApp";
|
|
15
|
+
import {authAsUser, setupDb, UserModel} from "../tests";
|
|
16
|
+
import {z} from "../zodOpenApi";
|
|
17
|
+
import {clearMCPRegistry} from "./registry";
|
|
18
|
+
import {getAllMCPTools} from "./toolGenerator";
|
|
19
|
+
|
|
20
|
+
const typedUserModel = UserModel as unknown as UserModelType;
|
|
21
|
+
|
|
22
|
+
interface Widget {
|
|
23
|
+
_id: mongoose.Types.ObjectId;
|
|
24
|
+
name: string;
|
|
25
|
+
ownerId?: mongoose.Types.ObjectId;
|
|
26
|
+
stars: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const widgetSchema = new Schema<Widget>({
|
|
30
|
+
name: {description: "Widget name", type: String},
|
|
31
|
+
ownerId: {description: "Owner of the widget", type: Schema.Types.ObjectId},
|
|
32
|
+
stars: {default: 0, description: "Star count", type: Number},
|
|
33
|
+
});
|
|
34
|
+
widgetSchema.plugin(createdUpdatedPlugin);
|
|
35
|
+
const WidgetModel =
|
|
36
|
+
(mongoose.models.McpActionWidget as mongoose.Model<Widget> | undefined) ??
|
|
37
|
+
model<Widget>("McpActionWidget", widgetSchema);
|
|
38
|
+
|
|
39
|
+
const crudPermissions = {
|
|
40
|
+
create: [Permissions.IsAuthenticated],
|
|
41
|
+
delete: [],
|
|
42
|
+
list: [Permissions.IsAuthenticated],
|
|
43
|
+
read: [Permissions.IsAuthenticated],
|
|
44
|
+
update: [Permissions.IsAuthenticated],
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Owner-only, checked after the document loads; passes the pre-document check. */
|
|
48
|
+
const isWidgetOwner = (_method: string, user?: {_id?: unknown}, obj?: unknown): boolean => {
|
|
49
|
+
if (!obj) {
|
|
50
|
+
return Boolean(user);
|
|
51
|
+
}
|
|
52
|
+
return String((obj as Widget).ownerId) === String(user?._id);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const widgetRouter = (extra: Record<string, unknown> = {}) =>
|
|
56
|
+
modelRouter("/widgets", WidgetModel, {
|
|
57
|
+
collectionActions: {
|
|
58
|
+
countMine: {
|
|
59
|
+
handler: async ({req, user}) => ({
|
|
60
|
+
count: await WidgetModel.countDocuments({ownerId: user?._id}),
|
|
61
|
+
credential: getCurrentRequestContext()?.credential ?? null,
|
|
62
|
+
isMCPRequest: (req as unknown as {isMCPRequest?: boolean}).isMCPRequest ?? false,
|
|
63
|
+
}),
|
|
64
|
+
mcp: {description: "Count the caller's widgets", name: "widgets_count_mine"},
|
|
65
|
+
method: "GET",
|
|
66
|
+
permissions: [Permissions.IsAuthenticated],
|
|
67
|
+
},
|
|
68
|
+
echoId: {
|
|
69
|
+
body: z.object({id: z.string()}).strict(),
|
|
70
|
+
handler: async ({body}) => ({id: body.id}),
|
|
71
|
+
mcp: {name: "widgets_echo_id"},
|
|
72
|
+
method: "POST",
|
|
73
|
+
permissions: [Permissions.IsAuthenticated],
|
|
74
|
+
},
|
|
75
|
+
writesRes: {
|
|
76
|
+
handler: async ({res}) => {
|
|
77
|
+
res.status(201).json({raw: true});
|
|
78
|
+
return undefined;
|
|
79
|
+
},
|
|
80
|
+
mcp: {name: "widgets_writes_res"},
|
|
81
|
+
method: "POST",
|
|
82
|
+
permissions: [Permissions.IsAuthenticated],
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
instanceActions: {
|
|
86
|
+
peek: {
|
|
87
|
+
handler: async ({doc, query}) => ({name: doc.name, verbose: query.verbose}),
|
|
88
|
+
mcp: {name: "widgets_peek"},
|
|
89
|
+
method: "GET",
|
|
90
|
+
permissions: [Permissions.IsAuthenticated],
|
|
91
|
+
query: z.object({verbose: z.boolean().optional()}),
|
|
92
|
+
},
|
|
93
|
+
star: {
|
|
94
|
+
body: z.object({amount: z.number().int().min(1)}).strict(),
|
|
95
|
+
description: "Add stars to a widget",
|
|
96
|
+
handler: async ({body, doc, req}) => {
|
|
97
|
+
await WidgetModel.updateOne({_id: doc._id}, {$inc: {stars: body.amount}});
|
|
98
|
+
return {
|
|
99
|
+
isMCPRequest: (req as unknown as {isMCPRequest?: boolean}).isMCPRequest ?? false,
|
|
100
|
+
stars: doc.stars + body.amount,
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
mcp: {name: "widgets_star"},
|
|
104
|
+
method: "POST",
|
|
105
|
+
permissions: [isWidgetOwner],
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
permissions: crudPermissions,
|
|
109
|
+
...extra,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
interface ToolCallResult {
|
|
113
|
+
content: Array<{text: string; type: string}>;
|
|
114
|
+
isError?: boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Streamable HTTP may answer as JSON or as one SSE `data:` frame; accept either. */
|
|
118
|
+
const parseJsonRpc = (text: string): {result?: Record<string, unknown>} => {
|
|
119
|
+
const dataLine = text.split("\n").find((line) => line.startsWith("data:"));
|
|
120
|
+
return JSON.parse(dataLine ? dataLine.slice("data:".length) : text);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const mcpPost = (
|
|
124
|
+
client: TestAgent | supertest.Agent | ReturnType<typeof supertest>,
|
|
125
|
+
body: Record<string, unknown>,
|
|
126
|
+
bearer?: string
|
|
127
|
+
) => {
|
|
128
|
+
const request = (client as ReturnType<typeof supertest>)
|
|
129
|
+
.post("/mcp")
|
|
130
|
+
.set("accept", "application/json, text/event-stream");
|
|
131
|
+
if (bearer) {
|
|
132
|
+
request.set("Authorization", `Bearer ${bearer}`);
|
|
133
|
+
}
|
|
134
|
+
return request.send(body);
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const callTool = async (
|
|
138
|
+
client: TestAgent | ReturnType<typeof supertest>,
|
|
139
|
+
name: string,
|
|
140
|
+
args: Record<string, unknown>,
|
|
141
|
+
bearer?: string
|
|
142
|
+
): Promise<ToolCallResult> => {
|
|
143
|
+
const res = await mcpPost(
|
|
144
|
+
client,
|
|
145
|
+
{id: 1, jsonrpc: "2.0", method: "tools/call", params: {arguments: args, name}},
|
|
146
|
+
bearer
|
|
147
|
+
);
|
|
148
|
+
return parseJsonRpc(res.text).result as unknown as ToolCallResult;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const toolJson = (result: ToolCallResult): Record<string, unknown> =>
|
|
152
|
+
JSON.parse(result.content[0].text);
|
|
153
|
+
|
|
154
|
+
describe("modelRouter actions as MCP tools", () => {
|
|
155
|
+
let app: express.Application;
|
|
156
|
+
let ownerAgent: TestAgent;
|
|
157
|
+
let adminAgent: TestAgent;
|
|
158
|
+
let ownerId: mongoose.Types.ObjectId;
|
|
159
|
+
|
|
160
|
+
beforeEach(async () => {
|
|
161
|
+
const [, notAdmin] = await setupDb();
|
|
162
|
+
ownerId = notAdmin._id as mongoose.Types.ObjectId;
|
|
163
|
+
await WidgetModel.deleteMany({});
|
|
164
|
+
await McpServiceToken.deleteMany({});
|
|
165
|
+
clearMCPRegistry();
|
|
166
|
+
app = new TerrenoApp({mcpServiceTokens: true, skipListen: true, userModel: typedUserModel})
|
|
167
|
+
.register(widgetRouter())
|
|
168
|
+
.build();
|
|
169
|
+
ownerAgent = await authAsUser(app, "notAdmin");
|
|
170
|
+
adminAgent = await authAsUser(app, "admin");
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("lists an instance action with {id, ...body} as its input schema", async () => {
|
|
174
|
+
const res = await mcpPost(ownerAgent, {id: 1, jsonrpc: "2.0", method: "tools/list"});
|
|
175
|
+
const tools = parseJsonRpc(res.text).result?.tools as Array<{
|
|
176
|
+
description: string;
|
|
177
|
+
inputSchema: {properties: Record<string, unknown>; required?: string[]};
|
|
178
|
+
name: string;
|
|
179
|
+
}>;
|
|
180
|
+
const star = tools.find((tool) => tool.name === "widgets_star");
|
|
181
|
+
expect(star?.description).toContain("Add stars to a widget");
|
|
182
|
+
expect(Object.keys(star?.inputSchema.properties ?? {}).sort()).toEqual(["amount", "id"]);
|
|
183
|
+
expect(star?.inputSchema.required?.sort()).toEqual(["amount", "id"]);
|
|
184
|
+
|
|
185
|
+
const countMine = tools.find((tool) => tool.name === "widgets_count_mine");
|
|
186
|
+
expect(countMine?.inputSchema.properties ?? {}).not.toHaveProperty("id");
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("runs the handler with an MCP request and returns its value as JSON", async () => {
|
|
190
|
+
const widget = await WidgetModel.create({name: "Mine", ownerId, stars: 1});
|
|
191
|
+
|
|
192
|
+
const result = await callTool(ownerAgent, "widgets_star", {amount: 2, id: String(widget._id)});
|
|
193
|
+
|
|
194
|
+
expect(result.isError).toBeFalsy();
|
|
195
|
+
expect(toolJson(result)).toEqual({isMCPRequest: true, stars: 3});
|
|
196
|
+
expect((await WidgetModel.findById(widget._id))?.stars).toBe(3);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("refuses over MCP and over REST from the same permission chain", async () => {
|
|
200
|
+
const widget = await WidgetModel.create({name: "Not the admin's", ownerId, stars: 0});
|
|
201
|
+
|
|
202
|
+
const mcpResult = await callTool(adminAgent, "widgets_star", {
|
|
203
|
+
amount: 1,
|
|
204
|
+
id: String(widget._id),
|
|
205
|
+
});
|
|
206
|
+
const restResult = await adminAgent.post(`/widgets/${widget._id}/star`).send({amount: 1});
|
|
207
|
+
|
|
208
|
+
expect(mcpResult.isError).toBe(true);
|
|
209
|
+
expect(toolJson(mcpResult).error).toBe("Access denied");
|
|
210
|
+
expect(restResult.status).toBe(403);
|
|
211
|
+
expect((await WidgetModel.findById(widget._id))?.stars).toBe(0);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("refuses over MCP and REST when RBAC access denies the action", async () => {
|
|
215
|
+
clearMCPRegistry();
|
|
216
|
+
const access = createAccess({
|
|
217
|
+
connection: mongoose.connection,
|
|
218
|
+
defaultRoles: [{displayName: "Viewer", name: "viewer", permissions: {widget: ["read"]}}],
|
|
219
|
+
statements: {...terrenoStatements, widget: ["read", "star"]},
|
|
220
|
+
});
|
|
221
|
+
await access.roles.seedDefaults();
|
|
222
|
+
await UserModel.updateOne({_id: ownerId}, {$set: {roles: ["viewer"]}});
|
|
223
|
+
const rbacApp = new TerrenoApp({
|
|
224
|
+
accessControl: access,
|
|
225
|
+
skipListen: true,
|
|
226
|
+
userModel: typedUserModel,
|
|
227
|
+
})
|
|
228
|
+
.register(
|
|
229
|
+
modelRouter("/rbac-widgets", WidgetModel, {
|
|
230
|
+
instanceActions: {
|
|
231
|
+
star: {
|
|
232
|
+
access: {action: "star", resource: "widget"},
|
|
233
|
+
handler: async () => ({ok: true}),
|
|
234
|
+
mcp: {name: "rbac_widgets_star"},
|
|
235
|
+
method: "POST",
|
|
236
|
+
permissions: [Permissions.IsAuthenticated],
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
permissions: crudPermissions,
|
|
240
|
+
})
|
|
241
|
+
)
|
|
242
|
+
.build();
|
|
243
|
+
const agent = await authAsUser(rbacApp, "notAdmin");
|
|
244
|
+
const widget = await WidgetModel.create({name: "RBAC", ownerId});
|
|
245
|
+
|
|
246
|
+
const mcpResult = await callTool(agent, "rbac_widgets_star", {id: String(widget._id)});
|
|
247
|
+
const restResult = await agent.post(`/rbac-widgets/${widget._id}/star`).send({});
|
|
248
|
+
|
|
249
|
+
expect(mcpResult.isError).toBe(true);
|
|
250
|
+
expect(toolJson(mcpResult).error).toBe("Access denied");
|
|
251
|
+
expect(restResult.status).toBe(405);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("rejects an MCP call without credentials", async () => {
|
|
255
|
+
const result = await callTool(supertest(app), "widgets_count_mine", {});
|
|
256
|
+
|
|
257
|
+
expect(result.isError).toBe(true);
|
|
258
|
+
expect(toolJson(result).error).toBe("Permission denied: authentication required");
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it("fails explicitly when the handler touches res during an MCP call", async () => {
|
|
262
|
+
const result = await callTool(ownerAgent, "widgets_writes_res", {});
|
|
263
|
+
|
|
264
|
+
expect(result.isError).toBe(true);
|
|
265
|
+
expect(toolJson(result).error).toBe("Action used res during an MCP call");
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
it("runs collection actions without an id", async () => {
|
|
269
|
+
await WidgetModel.create({name: "One", ownerId});
|
|
270
|
+
await WidgetModel.create({name: "Two", ownerId});
|
|
271
|
+
|
|
272
|
+
const result = await callTool(ownerAgent, "widgets_count_mine", {});
|
|
273
|
+
|
|
274
|
+
expect(toolJson(result)).toMatchObject({count: 2, isMCPRequest: true});
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it("passes an id argument through to a collection action's body", async () => {
|
|
278
|
+
const result = await callTool(ownerAgent, "widgets_echo_id", {id: "external-42"});
|
|
279
|
+
|
|
280
|
+
expect(toolJson(result)).toEqual({id: "external-42"});
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("passes GET action arguments as the query", async () => {
|
|
284
|
+
const widget = await WidgetModel.create({name: "Peeked", ownerId});
|
|
285
|
+
|
|
286
|
+
const result = await callTool(ownerAgent, "widgets_peek", {
|
|
287
|
+
id: String(widget._id),
|
|
288
|
+
verbose: true,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
expect(toolJson(result)).toEqual({name: "Peeked", verbose: true});
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("reports a missing document as a tool error", async () => {
|
|
295
|
+
const result = await callTool(ownerAgent, "widgets_peek", {
|
|
296
|
+
id: String(new mongoose.Types.ObjectId()),
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
expect(result.isError).toBe(true);
|
|
300
|
+
expect(toolJson(result).error).toBe("Document not found");
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
it("validates arguments against the action's body schema", async () => {
|
|
304
|
+
const widget = await WidgetModel.create({name: "Strict", ownerId});
|
|
305
|
+
const res = await mcpPost(ownerAgent, {
|
|
306
|
+
id: 1,
|
|
307
|
+
jsonrpc: "2.0",
|
|
308
|
+
method: "tools/call",
|
|
309
|
+
params: {arguments: {amount: 0, id: String(widget._id)}, name: "widgets_star"},
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
expect(res.text).toContain("Input validation error");
|
|
313
|
+
expect((await WidgetModel.findById(widget._id))?.stars).toBe(0);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("records the credential type inside the tool handler", async () => {
|
|
317
|
+
const created = await ownerAgent.post("/mcp/service-tokens").send({name: "Agent"});
|
|
318
|
+
const serviceToken = created.body.data.token as string;
|
|
319
|
+
|
|
320
|
+
const jwtResult = await callTool(ownerAgent, "widgets_count_mine", {});
|
|
321
|
+
const tokenResult = await callTool(supertest(app), "widgets_count_mine", {}, serviceToken);
|
|
322
|
+
|
|
323
|
+
expect(toolJson(jwtResult).credential).toBe("jwt");
|
|
324
|
+
expect(toolJson(tokenResult).credential).toBe("mcp-service-token");
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("leaves REST responses wrapped in {data} when unwrapResponse is unset", async () => {
|
|
328
|
+
const res = await ownerAgent.get("/widgets/countMine");
|
|
329
|
+
|
|
330
|
+
expect(res.status).toBe(200);
|
|
331
|
+
expect(res.body.data).toMatchObject({count: 0, credential: "jwt", isMCPRequest: false});
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
describe("unwrapResponse", () => {
|
|
336
|
+
let agent: TestAgent;
|
|
337
|
+
|
|
338
|
+
beforeEach(async () => {
|
|
339
|
+
await setupDb();
|
|
340
|
+
clearMCPRegistry();
|
|
341
|
+
const app = new TerrenoApp({skipListen: true, userModel: typedUserModel})
|
|
342
|
+
.register(
|
|
343
|
+
modelRouter("/unwrapped-widgets", WidgetModel, {
|
|
344
|
+
collectionActions: {
|
|
345
|
+
bare: {
|
|
346
|
+
handler: async () => ({ok: true}),
|
|
347
|
+
method: "POST",
|
|
348
|
+
permissions: [Permissions.IsAuthenticated],
|
|
349
|
+
response: z.object({ok: z.boolean()}),
|
|
350
|
+
status: 202,
|
|
351
|
+
unwrapResponse: true,
|
|
352
|
+
},
|
|
353
|
+
empty: {
|
|
354
|
+
handler: async () => undefined,
|
|
355
|
+
method: "POST",
|
|
356
|
+
permissions: [Permissions.IsAuthenticated],
|
|
357
|
+
status: 204,
|
|
358
|
+
unwrapResponse: true,
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
permissions: crudPermissions,
|
|
362
|
+
})
|
|
363
|
+
)
|
|
364
|
+
.build();
|
|
365
|
+
agent = await authAsUser(app, "notAdmin");
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
it("sends the bare return value with the configured status", async () => {
|
|
369
|
+
const res = await agent.post("/unwrapped-widgets/bare").send({});
|
|
370
|
+
|
|
371
|
+
expect(res.status).toBe(202);
|
|
372
|
+
expect(res.body).toMatchObject({ok: true});
|
|
373
|
+
expect(res.body).not.toHaveProperty("data");
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("sends an empty body when the handler returns undefined", async () => {
|
|
377
|
+
const res = await agent.post("/unwrapped-widgets/empty").send({});
|
|
378
|
+
|
|
379
|
+
expect(res.status).toBe(204);
|
|
380
|
+
expect(res.text).toBe("");
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
it("documents the bare response schema in OpenAPI", async () => {
|
|
384
|
+
const res = await agent.get("/openapi.json");
|
|
385
|
+
const schema =
|
|
386
|
+
res.body.paths["/unwrapped-widgets/bare"].post.responses["202"].content["application/json"]
|
|
387
|
+
.schema;
|
|
388
|
+
|
|
389
|
+
expect(schema.properties).toHaveProperty("ok");
|
|
390
|
+
expect(schema.properties).not.toHaveProperty("data");
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
describe("action mcp registration", () => {
|
|
395
|
+
beforeEach(() => {
|
|
396
|
+
clearMCPRegistry();
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const routerWith = (instanceActions: Record<string, unknown>) =>
|
|
400
|
+
modelRouter(WidgetModel, {
|
|
401
|
+
instanceActions: instanceActions as never,
|
|
402
|
+
permissions: crudPermissions,
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
it("rejects an invalid tool name", () => {
|
|
406
|
+
expect(() =>
|
|
407
|
+
routerWith({
|
|
408
|
+
star: {
|
|
409
|
+
handler: async () => ({}),
|
|
410
|
+
mcp: {name: "has space"},
|
|
411
|
+
method: "POST",
|
|
412
|
+
permissions: [],
|
|
413
|
+
},
|
|
414
|
+
})
|
|
415
|
+
).not.toThrow();
|
|
416
|
+
expect(() =>
|
|
417
|
+
routerWith({
|
|
418
|
+
star: {
|
|
419
|
+
handler: async () => ({}),
|
|
420
|
+
mcp: {name: "has space"},
|
|
421
|
+
method: "POST",
|
|
422
|
+
permissions: [Permissions.IsAny],
|
|
423
|
+
},
|
|
424
|
+
})
|
|
425
|
+
).toThrow(/invalid mcp.name/);
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
it("rejects a body schema that is not an object", () => {
|
|
429
|
+
expect(() =>
|
|
430
|
+
routerWith({
|
|
431
|
+
star: {
|
|
432
|
+
body: z.array(z.string()),
|
|
433
|
+
handler: async () => ({}),
|
|
434
|
+
mcp: {name: "widgets_star"},
|
|
435
|
+
method: "POST",
|
|
436
|
+
permissions: [Permissions.IsAny],
|
|
437
|
+
},
|
|
438
|
+
})
|
|
439
|
+
).toThrow(/body schema must be a z.object/);
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
it("rejects an instance body schema that defines id", () => {
|
|
443
|
+
expect(() =>
|
|
444
|
+
routerWith({
|
|
445
|
+
star: {
|
|
446
|
+
body: z.object({id: z.string()}),
|
|
447
|
+
handler: async () => ({}),
|
|
448
|
+
mcp: {name: "widgets_star"},
|
|
449
|
+
method: "POST",
|
|
450
|
+
permissions: [Permissions.IsAny],
|
|
451
|
+
},
|
|
452
|
+
})
|
|
453
|
+
).toThrow(/cannot define "id"/);
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
it("registers pathless routers so their action tools are listed", () => {
|
|
457
|
+
routerWith({
|
|
458
|
+
star: {
|
|
459
|
+
handler: async () => ({}),
|
|
460
|
+
mcp: {name: "pathless_widgets_star"},
|
|
461
|
+
method: "POST",
|
|
462
|
+
permissions: [Permissions.IsAny],
|
|
463
|
+
},
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
expect(getAllMCPTools().map((tool) => tool.name)).toContain("pathless_widgets_star");
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it("skips disabled actions", () => {
|
|
470
|
+
routerWith({
|
|
471
|
+
star: {
|
|
472
|
+
handler: async () => ({}),
|
|
473
|
+
mcp: {name: "disabled_widgets_star"},
|
|
474
|
+
method: "POST",
|
|
475
|
+
permissions: [],
|
|
476
|
+
},
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
expect(getAllMCPTools().map((tool) => tool.name)).not.toContain("disabled_widgets_star");
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it("throws when an action tool name collides with another tool", () => {
|
|
483
|
+
modelRouter(WidgetModel, {
|
|
484
|
+
instanceActions: {
|
|
485
|
+
star: {
|
|
486
|
+
handler: async () => ({}),
|
|
487
|
+
mcp: {name: "collide_list"},
|
|
488
|
+
method: "POST",
|
|
489
|
+
permissions: [Permissions.IsAny],
|
|
490
|
+
},
|
|
491
|
+
},
|
|
492
|
+
mcp: {methods: ["list"], toolPrefix: "collide"},
|
|
493
|
+
permissions: crudPermissions,
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
expect(() => getAllMCPTools()).toThrow(/used by more than one tool/);
|
|
497
|
+
});
|
|
498
|
+
});
|