From e04360f83e9a2937f94d7fc47e1f83c1715f9f4a Mon Sep 17 00:00:00 2001 From: andypalmi Date: Mon, 3 Aug 2026 16:12:33 +0200 Subject: [PATCH 1/2] feat(mcp): shared query schema fragments for platform tools Add forge/ee/lib/mcp/schemas.js, a shared module of composable zod fragments the platform read tools import instead of redefining entity-id and pagination/search/sort/audit-log query fields in each tool file. - entity-id params: teamId, applicationId, hostedInstanceId (UUID), remoteInstanceId, snapshotId - query fragments composed per route by spreading only the params the backing finder honors: cursorParam/limitParam (basePagination), pageParam, searchQuery, sortParams, auditLogFilters - appendQuery serialises a tool's supported params onto the request URL The module lives one level above tools/ so the tool loader does not register it as a tool module. Closes #7669 --- forge/ee/lib/mcp/schemas.js | 92 ++++++++++++++++++++++ test/unit/forge/ee/lib/mcp/schemas_spec.js | 76 ++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 forge/ee/lib/mcp/schemas.js create mode 100644 test/unit/forge/ee/lib/mcp/schemas_spec.js diff --git a/forge/ee/lib/mcp/schemas.js b/forge/ee/lib/mcp/schemas.js new file mode 100644 index 0000000000..03d628a008 --- /dev/null +++ b/forge/ee/lib/mcp/schemas.js @@ -0,0 +1,92 @@ +const { z } = require('zod') + +// Hosted instances are Projects (UUID primary key); the other entities use hashids. +const teamId = z.string().describe('The ID or hashid of the team') +const applicationId = z.string().describe('The ID or hashid of the application') +const hostedInstanceId = z.string().uuid().describe('The UUID of the hosted instance') +const remoteInstanceId = z.string().describe('The ID or hashid of the remote instance') +const snapshotId = z.string().describe('The hashid of the snapshot') + +// Query fragments composed per tool by spreading only the ones the backing +// route's finder actually honors. Not the same as the route's declared query +// schema: most list routes reuse a generic PaginationParams that advertises +// page/sort/dir/order even when the finder ignores them. Match the finder. + +const cursorParam = { + cursor: z.string().optional().describe('Opaque cursor from a previous page') +} +const limitParam = { + limit: z.number().int().min(1).max(50).default(10).describe('Maximum number of records to return (1-50, default 10)') +} +const basePagination = { ...cursorParam, ...limitParam } + +// Only Device.getAll and Project.byTeam read page and compute an offset. +const pageParam = { + page: z.number().int().min(1).optional().default(1).describe('1-based page number (offset pagination)') +} + +const searchQuery = { + query: z.string().optional().describe('Free-text search filter') +} + +// Only Project.byTeam honors sort; no finder reads the legacy `order` alias. +const sortParams = { + sort: z.string().optional().describe('Field name to sort by'), + dir: z.enum(['asc', 'desc']).optional().describe('Sort direction') +} + +// scope is route-specific (its enum differs per entity), so each tool declares it inline. +const auditLogFilters = { + event: z.union([z.string(), z.array(z.string())]).optional().describe('Filter by audit event name, or an array of event names'), + username: z.string().optional().describe('Filter by the username that triggered the event') +} + +const cursorParamKeys = Object.keys(cursorParam) +const limitParamKeys = Object.keys(limitParam) +const basePaginationKeys = Object.keys(basePagination) +const pageParamKeys = Object.keys(pageParam) +const searchQueryKeys = Object.keys(searchQuery) +const sortParamsKeys = Object.keys(sortParams) +const auditLogFilterKeys = Object.keys(auditLogFilters) + +// Serialise the given query keys from args onto a url: only defined values, +// URL-encoded, an array value appended once per element. +function appendQuery (url, args, keys) { + const params = new URLSearchParams() + for (const key of keys) { + const value = args[key] + if (value === undefined || value === null) { + continue + } + if (Array.isArray(value)) { + value.forEach(v => params.append(key, v)) + } else { + params.append(key, value) + } + } + const queryString = params.toString() + return queryString ? `${url}?${queryString}` : url +} + +module.exports = { + teamId, + applicationId, + hostedInstanceId, + remoteInstanceId, + snapshotId, + cursorParam, + limitParam, + basePagination, + pageParam, + searchQuery, + sortParams, + auditLogFilters, + cursorParamKeys, + limitParamKeys, + basePaginationKeys, + pageParamKeys, + searchQueryKeys, + sortParamsKeys, + auditLogFilterKeys, + appendQuery +} diff --git a/test/unit/forge/ee/lib/mcp/schemas_spec.js b/test/unit/forge/ee/lib/mcp/schemas_spec.js new file mode 100644 index 0000000000..ae9d953474 --- /dev/null +++ b/test/unit/forge/ee/lib/mcp/schemas_spec.js @@ -0,0 +1,76 @@ +const should = require('should') // eslint-disable-line no-unused-vars + +const FF_UTIL = require('flowforge-test-utils') + +const { + teamId, + applicationId, + hostedInstanceId, + remoteInstanceId, + snapshotId, + basePagination, + cursorParamKeys, + limitParamKeys, + basePaginationKeys, + pageParamKeys, + searchQueryKeys, + sortParamsKeys, + auditLogFilterKeys, + appendQuery +} = FF_UTIL.require('forge/ee/lib/mcp/schemas') + +describe('MCP shared query schemas', function () { + describe('entity-id params', function () { + it('hashid params accept any non-empty string', function () { + for (const param of [teamId, applicationId, remoteInstanceId, snapshotId]) { + param.parse('aBc123').should.equal('aBc123') + } + }) + it('hostedInstanceId accepts a UUID and rejects a hashid', function () { + hostedInstanceId.parse('4f8c1e2a-1b2c-4d3e-8f90-abcdef123456').should.be.a.String() + hostedInstanceId.safeParse('aBc123').success.should.equal(false) + }) + }) + + describe('fragment composition', function () { + it('basePagination is cursor plus limit only (no page)', function () { + basePaginationKeys.should.eql(['cursor', 'limit']) + }) + it('page, search and sort are separate opt-in fragments', function () { + cursorParamKeys.should.eql(['cursor']) + limitParamKeys.should.eql(['limit']) + pageParamKeys.should.eql(['page']) + searchQueryKeys.should.eql(['query']) + sortParamsKeys.should.eql(['sort', 'dir']) + auditLogFilterKeys.should.eql(['event', 'username']) + }) + it('key list matches the shape object it describes', function () { + basePaginationKeys.should.eql(Object.keys(basePagination)) + }) + }) + + describe('appendQuery', function () { + it('returns the url unchanged when no supported params are set', function () { + appendQuery('/api/v1/x', {}, basePaginationKeys).should.equal('/api/v1/x') + }) + it('returns the url unchanged when only unsupported keys are present', function () { + appendQuery('/api/v1/x', { teamId: 'abc' }, basePaginationKeys).should.equal('/api/v1/x') + }) + it('serialises only the defined, supported params', function () { + appendQuery('/api/v1/x', { limit: 10, page: 2, cursor: undefined }, [...basePaginationKeys, ...pageParamKeys]) + .should.equal('/api/v1/x?limit=10&page=2') + }) + it('url-encodes values', function () { + appendQuery('/api/v1/x', { query: 'a b&c' }, searchQueryKeys) + .should.equal('/api/v1/x?query=a+b%26c') + }) + it('appends an array value once per element', function () { + appendQuery('/api/v1/x', { event: ['flows.created', 'flows.deleted'] }, auditLogFilterKeys) + .should.equal('/api/v1/x?event=flows.created&event=flows.deleted') + }) + it('skips null and undefined but keeps other values', function () { + appendQuery('/api/v1/x', { limit: null, page: 1 }, [...basePaginationKeys, ...pageParamKeys]) + .should.equal('/api/v1/x?page=1') + }) + }) +}) From d91efd250d25c1d7a6d6651348148f44bad2b946 Mon Sep 17 00:00:00 2001 From: andypalmi Date: Mon, 3 Aug 2026 17:31:27 +0200 Subject: [PATCH 2/2] feat(mcp): add platform catalog read tools Add read-only MCP tools to list and get stacks, hosted instance types, templates, blueprints and team types by id, allow-listing their scopes for the expert-mcp platform token. --- forge/ee/lib/mcp/tools/platform.js | 61 ++++++ forge/routes/auth/permissions.js | 6 +- .../forge/ee/lib/mcp/tools/platform_spec.js | 204 ++++++++++++++++++ 3 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 test/unit/forge/ee/lib/mcp/tools/platform_spec.js diff --git a/forge/ee/lib/mcp/tools/platform.js b/forge/ee/lib/mcp/tools/platform.js index 19bf419365..901f2dd8d6 100644 --- a/forge/ee/lib/mcp/tools/platform.js +++ b/forge/ee/lib/mcp/tools/platform.js @@ -1,5 +1,7 @@ const { z } = require('zod') +const { basePagination, basePaginationKeys, searchQuery, searchQueryKeys, appendQuery } = require('../schemas') + function getProperty (properties, key) { let value = properties for (const part of key.split('.')) { @@ -98,5 +100,64 @@ module.exports = [ const response = await inject({ method: 'GET', url: '/api/v1/flow-blueprints' }) return response } + }, + { + name: 'platform_get_template', + title: 'Get Template', + description: 'Get a single template by id. Env values are blanked in the response.', + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + templateId: z.string().describe('Template hashid') + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/templates/${args.templateId}` }) + return response + } + }, + { + name: 'platform_get_blueprint', + title: 'Get Blueprint', + description: 'Get a single flow blueprint by id.', + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + flowBlueprintId: z.string().describe('Flow blueprint hashid') + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/flow-blueprints/${args.flowBlueprintId}` }) + return response + } + }, + { + name: 'platform_list_team_types', + title: 'List Team Types', + description: `FlowFuse platform automation tool: + Lists the team types (tiers/plans) available on the platform, with name search, active-state filtering and pagination. + Use this to see what team types exist before creating a team or to look up a team's current type.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + ...basePagination, + ...searchQuery, + filter: z.enum(['all', 'active', 'inactive']).optional().describe('Which team types to include by active state (default active only)') + }, + handler: async (args, { inject }) => { + const url = appendQuery('/api/v1/team-types', args, [...basePaginationKeys, ...searchQueryKeys, 'filter']) + const response = await inject({ method: 'GET', url }) + return response + } + }, + { + name: 'platform_get_team_type', + title: 'Get Team Type', + description: `FlowFuse platform automation tool: + Gets the details of a single team type by its hashid. + Use this to inspect the tier/plan a team is on, or to check a team type before assigning it to a new team.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamTypeId: z.string().describe('Team type hashid') + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/team-types/${args.teamTypeId}` }) + return response + } } ] diff --git a/forge/routes/auth/permissions.js b/forge/routes/auth/permissions.js index c1740abaa9..3a2185b69f 100644 --- a/forge/routes/auth/permissions.js +++ b/forge/routes/auth/permissions.js @@ -81,8 +81,12 @@ const IMPLICIT_TOKEN_SCOPES = { // platform 'stack:list', 'flow-blueprint:list', + 'flow-blueprint:read', 'project:status', - 'template:list' + 'template:list', + 'template:read', + 'team-type:list', // list team types + 'team-type:read' // get team type ] } diff --git a/test/unit/forge/ee/lib/mcp/tools/platform_spec.js b/test/unit/forge/ee/lib/mcp/tools/platform_spec.js new file mode 100644 index 0000000000..4ad43cc2a9 --- /dev/null +++ b/test/unit/forge/ee/lib/mcp/tools/platform_spec.js @@ -0,0 +1,204 @@ +const should = require('should') // eslint-disable-line no-unused-vars +const sinon = require('sinon') + +const tools = require('../../../../../../../forge/ee/lib/mcp/tools/platform') + +function getTool (name) { + return tools.find(tool => tool.name === name) +} + +describe('MCP Platform Catalog Tools', function () { + let inject + + beforeEach(function () { + inject = sinon.stub() + }) + + describe('platform_list_hosted_instance_types', function () { + const tool = getTool('platform_list_hosted_instance_types') + + it('decorates each type with availability, creatable flags and its stacks', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 200, + json: () => ({ + properties: { instances: { type1: { active: true } } }, + type: { properties: {} }, + instanceCountByType: {} + }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/project-types' }).resolves({ + statusCode: 200, + json: () => ({ types: [{ id: 'type1', name: 'small' }] }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/stacks?projectType=type1' }).resolves({ + statusCode: 200, + json: () => ({ stacks: [{ id: 'stack1', name: 'v3' }] }) + }) + + const response = await tool.handler({ teamId: 'team1' }, { inject }) + + response.should.eql({ + types: [ + { + id: 'type1', + name: 'small', + available: true, + creatable: true, + stacks: [{ id: 'stack1', name: 'v3' }] + } + ] + }) + }) + + it('includes non-creatable types when creatableOnly is false', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 200, + json: () => ({ properties: {}, type: { properties: {} }, instanceCountByType: {} }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/project-types' }).resolves({ + statusCode: 200, + json: () => ({ types: [{ id: 'type1', name: 'small' }] }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/stacks?projectType=type1' }).resolves({ + statusCode: 200, + json: () => ({ stacks: [] }) + }) + + const response = await tool.handler({ teamId: 'team1', creatableOnly: false }, { inject }) + + response.types.should.have.length(1) + response.types[0].available.should.be.false() + response.types[0].creatable.should.be.false() + }) + + it('excludes non-creatable types by default', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 200, + json: () => ({ properties: {}, type: { properties: {} }, instanceCountByType: {} }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/project-types' }).resolves({ + statusCode: 200, + json: () => ({ types: [{ id: 'type1', name: 'small' }] }) + }) + + const response = await tool.handler({ teamId: 'team1' }, { inject }) + + response.types.should.have.length(0) + }) + + it('narrows to a single type when projectType is set', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 200, + json: () => ({ + properties: { instances: { type1: { active: true }, type2: { active: true } } }, + type: { properties: {} }, + instanceCountByType: {} + }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/project-types' }).resolves({ + statusCode: 200, + json: () => ({ types: [{ id: 'type1', name: 'small' }, { id: 'type2', name: 'large' }] }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/stacks?projectType=type1' }).resolves({ + statusCode: 200, + json: () => ({ stacks: [] }) + }) + + const response = await tool.handler({ teamId: 'team1', projectType: 'type1' }, { inject }) + + response.types.should.have.length(1) + response.types[0].id.should.equal('type1') + }) + + it('returns an error object when the team fetch fails', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 404, + json: () => ({ code: 'not_found' }) + }) + + const response = await tool.handler({ teamId: 'team1' }, { inject }) + + response.should.eql({ content: { code: 'not_found' }, code: 404, isError: true }) + }) + + it('returns an error object when the project-types fetch fails', async function () { + inject.withArgs({ method: 'GET', url: '/api/v1/teams/team1' }).resolves({ + statusCode: 200, + json: () => ({ properties: {}, type: { properties: {} }, instanceCountByType: {} }) + }) + inject.withArgs({ method: 'GET', url: '/api/v1/project-types' }).resolves({ + statusCode: 500, + json: () => ({ code: 'unexpected_error' }) + }) + + const response = await tool.handler({ teamId: 'team1' }, { inject }) + + response.should.eql({ content: { code: 'unexpected_error' }, code: 500, isError: true }) + }) + }) + + describe('platform_list_team_types', function () { + const tool = getTool('platform_list_team_types') + + it('serialises pagination, search and filter onto the team-types route', async function () { + const routeResponse = { statusCode: 200, json: () => ({ teamTypes: [] }) } + inject.withArgs({ + method: 'GET', + url: '/api/v1/team-types?cursor=c1&limit=20&query=ent&filter=active' + }).resolves(routeResponse) + + const response = await tool.handler({ + cursor: 'c1', + limit: 20, + query: 'ent', + filter: 'active' + }, { inject }) + + inject.calledOnce.should.be.true() + response.should.equal(routeResponse) + }) + + it('passes through an error response', async function () { + const errorResponse = { statusCode: 500, json: () => ({ code: 'unexpected_error' }) } + inject.resolves(errorResponse) + + const response = await tool.handler({ limit: 10 }, { inject }) + + response.should.equal(errorResponse) + }) + }) + + // Simple GET readers: each injects one URL and returns the response verbatim. + const passthroughGetTools = [ + { name: 'platform_list_templates', args: {}, url: '/api/v1/templates' }, + { name: 'platform_list_blueprints', args: {}, url: '/api/v1/flow-blueprints' }, + { name: 'platform_get_template', args: { templateId: 'tmpl1' }, url: '/api/v1/templates/tmpl1' }, + { name: 'platform_get_blueprint', args: { flowBlueprintId: 'bp1' }, url: '/api/v1/flow-blueprints/bp1' }, + { name: 'platform_get_team_type', args: { teamTypeId: 'tt1' }, url: '/api/v1/team-types/tt1' } + ] + + passthroughGetTools.forEach(({ name, args, url }) => { + describe(name, function () { + const tool = getTool(name) + + it(`injects GET ${url} and returns the response`, async function () { + const routeResponse = { statusCode: 200, json: () => ({ ok: true }) } + inject.withArgs({ method: 'GET', url }).resolves(routeResponse) + + const response = await tool.handler(args, { inject }) + + inject.calledOnce.should.be.true() + response.should.equal(routeResponse) + }) + + it('passes through an error response', async function () { + const errorResponse = { statusCode: 404, json: () => ({ code: 'not_found' }) } + inject.resolves(errorResponse) + + const response = await tool.handler(args, { inject }) + + response.should.equal(errorResponse) + }) + }) + }) +})