diff --git a/forge/ee/lib/mcp/tools/teams.js b/forge/ee/lib/mcp/tools/teams.js index ecc053113b..32c318e4ba 100644 --- a/forge/ee/lib/mcp/tools/teams.js +++ b/forge/ee/lib/mcp/tools/teams.js @@ -1,5 +1,14 @@ const { z } = require('zod') +const { teamId, basePagination, basePaginationKeys, searchQuery, searchQueryKeys, auditLogFilters, auditLogFilterKeys, appendQuery } = require('../schemas') + +// Audit-log routes accept cursor+limit pagination, free-text query, event +// (single name or array) and username. scope narrows which entity levels are +// returned; includeChildren pulls in descendant entries within the chosen scope. +const includeChildren = z.boolean().optional().describe('Also include audit entries from child entities within the chosen scope') +const auditLogInput = { ...basePagination, ...searchQuery, ...auditLogFilters } +const auditLogKeys = [...basePaginationKeys, ...searchQueryKeys, ...auditLogFilterKeys] + module.exports = [ { name: 'platform_list_teams', @@ -18,11 +27,197 @@ module.exports = [ description: 'FlowFuse platform automation tool: Get details of a specific team by its ID, including team type, member count, hosted instance and remote instance counts.', annotations: { readOnlyHint: true, destructiveHint: false }, inputSchema: { - teamId: z.string().describe('The ID or hashid of the team') + teamId }, handler: async (args, { inject }) => { const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}` }) return response } + }, + { + name: 'platform_get_team_by_slug', + title: 'Get Team By Slug', + description: `FlowFuse platform automation tool: + Gets details of a specific team using its slug (URL identifier) instead of its hashid. + Use this when you only know the team's slug, for example from a URL, and need the same details as platform_get_team.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamSlug: z.string().regex(/^[a-z0-9-_]+$/i).describe('Team slug (URL identifier; lowercase letters, digits, hyphen and underscore)') + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/slug/${args.teamSlug}` }) + return response + } + }, + { + name: 'platform_get_team_instance_counts', + title: 'Get Team Instance Counts', + description: `FlowFuse platform automation tool: + Counts a team's instances of the given type, optionally narrowed by state and application. + instanceType is required: use "hosted" for hosted instances or "remote" for remote instances (devices). + Use this for quick totals instead of listing and counting every instance yourself.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId, + instanceType: z.enum(['remote', 'hosted']).describe('Instance type to count'), + state: z.array(z.string()).optional().describe('Optional list of instance states to filter the counts by (defaults to empty)'), + applicationId: z.string().optional().describe('Application hashid to scope the counts to a single application') + }, + handler: async (args, { inject }) => { + const url = appendQuery(`/api/v1/teams/${args.teamId}/instance-counts`, args, ['instanceType', 'state', 'applicationId']) + const response = await inject({ method: 'GET', url }) + return response + } + }, + { + name: 'platform_check_team_slug_availability', + title: 'Check Team Slug Availability', + description: `FlowFuse platform automation tool: + Checks whether a team slug is available before creating a team. This does not create or change anything. + The value "create" is reserved and is always rejected. + Use this before calling a team creation tool to make sure the chosen slug is not already taken.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + slug: z.string().regex(/^[a-z0-9-_]+$/i).describe('Team slug to check; lowercase letters, digits, hyphen and underscore') + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'POST', url: '/api/v1/teams/check-slug', payload: { slug: args.slug } }) + return response + } + }, + { + name: 'platform_get_team_membership', + title: 'Get Team Membership', + description: `FlowFuse platform automation tool: + Gets the authenticated user's own membership (role) in a team. + Use this to check what role the current user holds in a team before attempting an action that needs a specific role.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}/user` }) + return response + } + }, + { + name: 'platform_list_team_members', + title: 'List Team Members', + description: `FlowFuse platform automation tool: + Lists the members of a team, including their role and, when SSO is enabled, whether their membership is SSO-managed. + Use this to see who belongs to a team before inviting, removing, or changing the role of a member.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}/members` }) + return response + } + }, + { + name: 'platform_list_team_invitations', + title: 'List Team Invitations', + description: `FlowFuse platform automation tool: + Lists the pending invitations for a team. + This requires the Owner role, so a non-Owner credential will get an access error even though this tool itself is read-only.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}/invitations` }) + return response + } + }, + { + name: 'platform_get_team_audit_log', + title: 'Get Team Audit Log', + description: `FlowFuse platform automation tool: + Reads the audit log for a team, showing events like membership changes, billing changes, + and administrative actions taken across the team's applications, instances, and devices. + A team-scoped PAT only sees audit log entries for teams it is scoped to. + Use this when the user asks what happened on a team, or wants to investigate recent changes.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId, + ...auditLogInput, + scope: z.enum(['team', 'application', 'project', 'device']).optional().describe('Entity level to include (default team)'), + includeChildren + }, + handler: async (args, { inject }) => { + const url = appendQuery(`/api/v1/teams/${args.teamId}/audit-log`, args, [...auditLogKeys, 'scope', 'includeChildren']) + const response = await inject({ method: 'GET', url }) + return response + } + }, + { + name: 'platform_export_team_audit_log', + title: 'Export Team Audit Log', + description: `FlowFuse platform automation tool: + Exports the team audit log as a CSV file. + Use this when the user wants a downloadable or shareable copy of the team's audit history, + rather than reading entries directly with platform_get_team_audit_log.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId, + ...auditLogInput, + scope: z.enum(['team', 'application', 'project', 'device']).optional().describe('Entity level to include (default team)'), + includeChildren + }, + handler: async (args, { inject }) => { + const url = appendQuery(`/api/v1/teams/${args.teamId}/audit-log/export`, args, [...auditLogKeys, 'scope', 'includeChildren']) + const response = await inject({ method: 'GET', url }) + return response + } + }, + { + name: 'platform_list_team_npm_packages', + title: 'List Team NPM Packages', + description: `FlowFuse platform automation tool: + Lists the private npm packages owned by a team. + The npm registry is a plan-gated feature; if it is not enabled for the team's plan, or the team does not exist, the underlying API's error response is returned as-is.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}/npm/packages` }) + return response + } + }, + { + name: 'platform_list_team_git_tokens', + title: 'List Team Git Tokens', + description: `FlowFuse platform automation tool: + Lists the git tokens configured for a team. The response never includes the raw stored personal access token, only its ID, name, and type. + Git integration is a plan-gated feature; if it is not enabled for the team's plan, or the team does not exist, the underlying API's error response is returned as-is.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + teamId + }, + handler: async (args, { inject }) => { + const response = await inject({ method: 'GET', url: `/api/v1/teams/${args.teamId}/git/tokens` }) + return response + } + }, + { + name: 'platform_list_library_entries', + title: 'List Library Entries', + description: `FlowFuse platform automation tool: + Lists entries in the team shared library (reusable flows, functions, and other snippets shared across a team's hosted and remote instances). + Pass an empty path to list the library root, or a folder path to list its contents. + The shared library is enabled by default, but a team may still not exist or the caller may not be a member; either case returns the underlying API's error response as-is.`, + annotations: { readOnlyHint: true, destructiveHint: false }, + inputSchema: { + libraryId: z.string().describe('shared-library hashid (the team hashid)'), + path: z.string().default('').describe('Library entry path; empty string lists the library root'), + type: z.string().optional().describe('entry type filter query param (e.g. flows, functions)') + }, + handler: async (args, { inject }) => { + const url = appendQuery(`/storage/library/${args.libraryId}/${args.path || ''}`, args, ['type']) + const response = await inject({ method: 'GET', url }) + return response + } } ] diff --git a/forge/ee/routes/sharedLibrary/index.js b/forge/ee/routes/sharedLibrary/index.js index 52017ad92d..ea0f60d2db 100644 --- a/forge/ee/routes/sharedLibrary/index.js +++ b/forge/ee/routes/sharedLibrary/index.js @@ -25,9 +25,9 @@ module.exports = async function (app) { // Device exists and the auth token is for this team return } - } else if (!request.session.ownerType) { - // This is a logged-in user. Get their teamMembership so the needsPermission - // checks in the routes will evaluate properly + } else if (!request.session.ownerType || request.session.ownerType === 'user' || request.session.ownerType === 'user:expert-mcp') { + // Cookie sessions and personal/platform-automation tokens both populate + // request.session.User the same way (see forge/routes/auth/index.js). request.teamMembership = await request.session.User.getTeamMembership(request.team.id) if (request.teamMembership) { return diff --git a/forge/routes/auth/permissions.js b/forge/routes/auth/permissions.js index 15a713be0c..8c71747ca3 100644 --- a/forge/routes/auth/permissions.js +++ b/forge/routes/auth/permissions.js @@ -48,6 +48,14 @@ const IMPLICIT_TOKEN_SCOPES = { // teams 'user:team:list', // list teams 'team:read', // get team details + 'team:user:list', // list team members + 'team:user:invite', // list team invitations + 'team:create', // check team slug availability + 'team:audit-log', // get team audit log + // team data + 'team:packages:read', // list team npm packages + 'team:git:tokens:list', // list team git tokens + 'library:entry:list', // list team shared library entries // platform 'stack:list', 'flow-blueprint:list', diff --git a/test/unit/forge/ee/lib/mcp/tools/teams_spec.js b/test/unit/forge/ee/lib/mcp/tools/teams_spec.js new file mode 100644 index 0000000000..0bb102f5b4 --- /dev/null +++ b/test/unit/forge/ee/lib/mcp/tools/teams_spec.js @@ -0,0 +1,603 @@ +const should = require('should') // eslint-disable-line no-unused-vars +const sinon = require('sinon') + +const { expectToolMatchesRoute, createExpertMcpToken, toolFinder, recordingInject } = require('../../../../../../lib/mcpToolEquivalence') + +const FF_UTIL = require('flowforge-test-utils') + +const tools = FF_UTIL.require('forge/ee/lib/mcp/tools/teams') +const { basePaginationKeys, searchQueryKeys, auditLogFilterKeys } = FF_UTIL.require('forge/ee/lib/mcp/schemas') +const findTool = toolFinder(tools) + +// audit-log routes honor cursor+limit, free-text query, and event/username. +// The team routes also honor scope + includeChildren. +const auditLogKeys = [...basePaginationKeys, ...searchQueryKeys, ...auditLogFilterKeys] +const auditLogScopedKeys = [...auditLogKeys, 'scope', 'includeChildren'] + +function jsonResponse (statusCode, body) { + return { statusCode, json: () => body } +} + +describe('MCP teams tools', function () { + it('exposes exactly the expected tool names', function () { + tools.map(t => t.name).should.eql([ + 'platform_list_teams', + 'platform_get_team', + 'platform_get_team_by_slug', + 'platform_get_team_instance_counts', + 'platform_check_team_slug_availability', + 'platform_get_team_membership', + 'platform_list_team_members', + 'platform_list_team_invitations', + 'platform_get_team_audit_log', + 'platform_export_team_audit_log', + 'platform_list_team_npm_packages', + 'platform_list_team_git_tokens', + 'platform_list_library_entries' + ]) + }) + + it('every tool is annotated as read-only and non-destructive', function () { + tools.forEach(tool => { + tool.annotations.should.have.property('readOnlyHint', true) + tool.annotations.should.have.property('destructiveHint', false) + }) + }) + + describe('platform_list_teams', function () { + const tool = findTool('platform_list_teams') + + it('has no input params', function () { + Object.keys(tool.inputSchema).should.eql([]) + }) + + it('calls GET /api/v1/user/teams', async function () { + const { calls, inject } = recordingInject() + await tool.handler({}, { inject }) + calls.should.have.length(1) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/user/teams') + }) + }) + + describe('platform_get_team', function () { + const tool = findTool('platform_get_team') + + it('has the teamId input', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET /api/v1/teams/:teamId', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1') + }) + }) + + describe('platform_get_team_by_slug', function () { + const tool = findTool('platform_get_team_by_slug') + + it('has the teamSlug input', function () { + Object.keys(tool.inputSchema).should.eql(['teamSlug']) + }) + + it('calls GET /api/v1/teams/slug/:teamSlug', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamSlug: 'my-team' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/slug/my-team') + }) + }) + + describe('platform_get_team_instance_counts', function () { + const tool = findTool('platform_get_team_instance_counts') + + it('has the expected input params', function () { + Object.keys(tool.inputSchema).should.eql(['teamId', 'instanceType', 'state', 'applicationId']) + }) + + it('serialises a state array as repeated params', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1', instanceType: 'hosted', state: ['running', 'stopped'] }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/instance-counts?instanceType=hosted&state=running&state=stopped') + }) + + it('includes applicationId when set and omits state when not provided', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1', instanceType: 'remote', applicationId: 'app1' }, { inject }) + calls[0].url.should.equal('/api/v1/teams/team1/instance-counts?instanceType=remote&applicationId=app1') + }) + }) + + describe('platform_check_team_slug_availability', function () { + const tool = findTool('platform_check_team_slug_availability') + + it('has the slug input', function () { + Object.keys(tool.inputSchema).should.eql(['slug']) + }) + + it('calls POST /api/v1/teams/check-slug with the slug payload', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ slug: 'my-team' }, { inject }) + calls[0].method.should.equal('POST') + calls[0].url.should.equal('/api/v1/teams/check-slug') + calls[0].payload.should.eql({ slug: 'my-team' }) + }) + }) + + describe('platform_get_team_membership', function () { + const tool = findTool('platform_get_team_membership') + + it('has the teamId input', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET /api/v1/teams/:teamId/user', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1' }, { inject }) + calls.should.have.length(1) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/user') + }) + }) + + describe('platform_list_team_members', function () { + const tool = findTool('platform_list_team_members') + + it('has the teamId input', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET /api/v1/teams/:teamId/members', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/members') + }) + }) + + describe('platform_list_team_invitations', function () { + const tool = findTool('platform_list_team_invitations') + + it('has the teamId input', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET /api/v1/teams/:teamId/invitations', async function () { + const { calls, inject } = recordingInject() + await tool.handler({ teamId: 'team1' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/invitations') + }) + }) + + describe('team audit-log tools', function () { + function stubInject (response = { statusCode: 200, json: () => ({}) }) { + return sinon.stub().resolves(response) + } + + const toolDefinitions = [ + { + name: 'platform_get_team_audit_log', + base: id => `/api/v1/teams/${id}/audit-log` + }, + { + name: 'platform_export_team_audit_log', + base: id => `/api/v1/teams/${id}/audit-log/export` + } + ] + + toolDefinitions.forEach(def => { + describe(def.name, function () { + it('exposes the expected inputSchema keys', function () { + const tool = findTool(def.name) + const expectedKeys = ['teamId', ...auditLogScopedKeys] + Object.keys(tool.inputSchema).sort().should.deepEqual(expectedKeys.sort()) + }) + + it('calls inject with the correct method and bare URL when no query params are given', async function () { + const tool = findTool(def.name) + const inject = stubInject() + await tool.handler({ teamId: 'abc123' }, { inject }) + inject.calledOnce.should.be.true() + const call = inject.firstCall.args[0] + call.method.should.equal('GET') + call.url.should.equal(def.base('abc123')) + }) + + it('serialises pagination params onto the URL', async function () { + const tool = findTool(def.name) + const inject = stubInject() + await tool.handler({ teamId: 'abc123', limit: 10 }, { inject }) + const call = inject.firstCall.args[0] + call.url.should.equal(`${def.base('abc123')}?limit=10`) + }) + }) + }) + + it('serialises an array `event` filter as one repeated query param per element', async function () { + const tool = findTool('platform_get_team_audit_log') + const inject = stubInject() + await tool.handler({ teamId: 'team1', event: ['user.login', 'user.logout'], limit: 5 }, { inject }) + const call = inject.firstCall.args[0] + call.url.should.equal('/api/v1/teams/team1/audit-log?limit=5&event=user.login&event=user.logout') + }) + + it('serialises the `username` filter alongside other query params', async function () { + const tool = findTool('platform_get_team_audit_log') + const inject = stubInject() + await tool.handler({ teamId: 'team1', username: 'alice', limit: 20 }, { inject }) + const call = inject.firstCall.args[0] + call.url.should.equal('/api/v1/teams/team1/audit-log?limit=20&username=alice') + }) + + it('serialises the scope and includeChildren filters', async function () { + const tool = findTool('platform_get_team_audit_log') + const inject = stubInject() + await tool.handler({ teamId: 'team1', scope: 'application', includeChildren: true }, { inject }) + const call = inject.firstCall.args[0] + call.url.should.equal('/api/v1/teams/team1/audit-log?scope=application&includeChildren=true') + }) + }) + + describe('platform_list_team_npm_packages', function () { + const tool = findTool('platform_list_team_npm_packages') + + it('declares the expected inputSchema keys', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET on the npm packages endpoint and returns the response unchanged', async function () { + const response = jsonResponse(200, [{ name: '@team/pkg' }]) + const { calls, inject } = recordingInject(response) + const result = await tool.handler({ teamId: 'team1' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/npm/packages') + result.should.equal(response) + }) + }) + + describe('platform_list_team_git_tokens', function () { + const tool = findTool('platform_list_team_git_tokens') + + it('declares the expected inputSchema keys', function () { + Object.keys(tool.inputSchema).should.eql(['teamId']) + }) + + it('calls GET on the git tokens endpoint and returns the response unchanged', async function () { + const response = jsonResponse(200, [{ id: 'tok1', name: 'ci-token', type: 'github' }]) + const { calls, inject } = recordingInject(response) + const result = await tool.handler({ teamId: 'team1' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/api/v1/teams/team1/git/tokens') + result.should.equal(response) + }) + }) + + describe('platform_list_library_entries', function () { + const tool = findTool('platform_list_library_entries') + + it('declares the expected inputSchema keys', function () { + Object.keys(tool.inputSchema).should.eql(['libraryId', 'path', 'type']) + }) + + it('lists the library root when path is empty and no type filter is given', async function () { + const response = jsonResponse(200, []) + const { calls, inject } = recordingInject(response) + const result = await tool.handler({ libraryId: 'team1', path: '' }, { inject }) + calls[0].method.should.equal('GET') + calls[0].url.should.equal('/storage/library/team1/') + result.should.equal(response) + }) + + it('lists a folder path and appends the type filter as a query param', async function () { + const { calls, inject } = recordingInject(jsonResponse(200, [])) + await tool.handler({ libraryId: 'team1', path: 'folder1', type: 'flows' }, { inject }) + calls[0].url.should.equal('/storage/library/team1/folder1?type=flows') + }) + }) +}) + +describe('MCP teams tools smoke test', function () { + const setup = require('../../../setup') + + let app + let token + + before(async function () { + app = await setup({ ai: { enabled: true }, expert: { enabled: true } }) + // check-slug requires 'team:create', gated behind this setting for non-admin callers like the expert-mcp token below + await app.settings.set('team:create', true) + token = await createExpertMcpToken(app) + }) + + after(async function () { + await app.close() + }) + + function inject (options) { + return app.inject({ + ...options, + headers: { + ...(options.headers || {}), + authorization: `Bearer ${token}` + } + }) + } + + describe('tool responses match their backing routes', function () { + it('platform_list_teams matches GET /api/v1/user/teams', async function () { + const tool = findTool('platform_list_teams') + await expectToolMatchesRoute(inject, tool, {}, { + method: 'GET', + url: '/api/v1/user/teams' + }) + }) + + it('platform_get_team matches GET /api/v1/teams/:teamId', async function () { + const tool = findTool('platform_get_team') + await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}` + }) + }) + + it('platform_get_team_by_slug matches GET /api/v1/teams/slug/:teamSlug', async function () { + const tool = findTool('platform_get_team_by_slug') + await expectToolMatchesRoute(inject, tool, { teamSlug: app.team.slug }, { + method: 'GET', + url: `/api/v1/teams/slug/${app.team.slug}` + }) + }) + + it('platform_get_team_instance_counts matches GET /api/v1/teams/:teamId/instance-counts', async function () { + const tool = findTool('platform_get_team_instance_counts') + await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid, instanceType: 'hosted' }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/instance-counts?instanceType=hosted` + }) + }) + + it('platform_check_team_slug_availability matches POST /api/v1/teams/check-slug for an available slug', async function () { + const tool = findTool('platform_check_team_slug_availability') + await expectToolMatchesRoute(inject, tool, { slug: 'a-brand-new-team-slug' }, { + method: 'POST', + url: '/api/v1/teams/check-slug', + payload: { slug: 'a-brand-new-team-slug' } + }) + }) + + it('platform_check_team_slug_availability matches POST /api/v1/teams/check-slug for a taken slug', async function () { + const tool = findTool('platform_check_team_slug_availability') + const { viaTool } = await expectToolMatchesRoute(inject, tool, { slug: app.team.slug }, { + method: 'POST', + url: '/api/v1/teams/check-slug', + payload: { slug: app.team.slug } + }) + viaTool.statusCode.should.equal(409) + }) + + it('platform_get_team_membership matches GET /api/v1/teams/:teamId/user', async function () { + const tool = findTool('platform_get_team_membership') + await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/user` + }) + }) + + it('platform_list_team_members matches GET /api/v1/teams/:teamId/members', async function () { + const tool = findTool('platform_list_team_members') + const { routeResponse } = await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/members` + }) + routeResponse.statusCode.should.equal(200) + routeResponse.json().members.should.not.be.empty() + }) + + it('platform_list_team_invitations matches GET /api/v1/teams/:teamId/invitations', async function () { + const bob = await app.factory.createUser({ + admin: false, + username: 'bob-invitee', + name: 'Bob Invitee', + email: 'bob-invitee@example.com', + password: 'bbPassword' + }) + await app.factory.createInvitation(app.team, app.user, bob) + + const tool = findTool('platform_list_team_invitations') + const { routeResponse } = await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/invitations` + }) + routeResponse.statusCode.should.equal(200) + routeResponse.json().invitations.should.not.be.empty() + }) + }) +}) + +describe('MCP teams audit-log tools - integration smoke', function () { + const setup = require('../../../setup') + + let app + let token + + before(async function () { + app = await setup({ + ai: { enabled: true }, + expert: { enabled: true } + }) + token = await createExpertMcpToken(app) + }) + + after(async function () { + await app.close() + }) + + function inject (options) { + return app.inject({ + ...options, + headers: { + ...(options.headers || {}), + authorization: `Bearer ${token}` + } + }) + } + + it('reads the team audit log via the underlying route', async function () { + const tool = findTool('platform_get_team_audit_log') + + const response = await tool.handler({ teamId: app.team.hashid }, { inject }) + + response.statusCode.should.equal(200) + const body = response.json() + body.should.have.property('meta') + body.should.have.property('count') + body.should.have.property('log') + body.log.should.be.an.Array() + }) + + describe('tool-vs-route equivalence', function () { + let team + + before(async function () { + team = app.team + + // Seed one real entry so assertions compare actual data, not an empty-list shape. + await app.db.controllers.AuditLog.teamLog(team.id, app.user.id, 'team.settings.updated', { settings: { name: team.name } }) + }) + + it('platform_get_team_audit_log matches GET /api/v1/teams/:teamId/audit-log, including query params', async function () { + const tool = findTool('platform_get_team_audit_log') + await expectToolMatchesRoute(inject, tool, { teamId: team.hashid, event: 'team.settings.updated', limit: 5 }, { + method: 'GET', + url: `/api/v1/teams/${team.hashid}/audit-log?limit=5&event=team.settings.updated` + }) + }) + + it('platform_export_team_audit_log matches GET /api/v1/teams/:teamId/audit-log/export', async function () { + const tool = findTool('platform_export_team_audit_log') + await expectToolMatchesRoute(inject, tool, { teamId: team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${team.hashid}/audit-log/export`, + raw: true + }) + }) + }) +}) + +describe('MCP teams data tools - integration smoke', function () { + const setup = require('../../../setup') + + const NPM_REGISTRY_PORT = 9761 + + let app + let token + let npmRegistryServer + + const inject = (options) => app.inject({ + ...options, + headers: { + ...(options.headers || {}), + authorization: `Bearer ${token}` + } + }) + + before(async function () { + app = await setup({ + ai: { enabled: true }, + expert: { enabled: true }, + npmRegistry: { + enabled: true, + url: `http://localhost:${NPM_REGISTRY_PORT}`, + admin: { username: 'admin', password: 'secret' } + } + }) + + // These features are off by default; enable them so the smoke test hits the real 200 path. + const defaultTeamTypeProperties = app.defaultTeamType.properties + defaultTeamTypeProperties.features = { + ...defaultTeamTypeProperties.features, + npm: true, + gitIntegration: true + } + app.defaultTeamType.properties = defaultTeamTypeProperties + await app.defaultTeamType.save() + + token = await createExpertMcpToken(app) + + // Minimal stand-in npm registry (pattern from catalogue/index_spec.js) so we get a real 200 response. + npmRegistryServer = require('http').createServer((req, res) => { + if (/^\/-\/all/.test(req.url)) { + res.writeHead(200, { 'Content-Type': 'application/json' }) + const body = { _updated: 99999 } + body[`@flowfuse-${app.team.hashid}/one`] = { + name: `@flowfuse-${app.team.hashid}/one`, + 'dist-tags': { latest: '1.0.0' }, + time: { modified: '2025-02-18T10:13:18.950Z' }, + license: 'Apache-2.0', + versions: { '1.0.0': 'latest' } + } + res.end(JSON.stringify(body)) + } else { + res.writeHead(404) + res.end() + } + }) + await new Promise((resolve) => npmRegistryServer.listen(NPM_REGISTRY_PORT, resolve)) + + await app.db.models.GitToken.create({ + name: 'ci-token', + token: 'ghp_smoketesttoken', + type: 'github', + TeamId: app.team.id + }) + + await app.db.models.StorageSharedLibrary.create({ + name: 'smoke-flow', + type: 'flows', + meta: JSON.stringify({}), + body: JSON.stringify([]), + TeamId: app.team.id + }) + }) + + after(async function () { + await app.close() + await new Promise((resolve) => npmRegistryServer.close(resolve)) + }) + + it('platform_list_team_npm_packages matches GET /api/v1/teams/:teamId/npm/packages', async function () { + const tool = findTool('platform_list_team_npm_packages') + const { viaTool } = await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/npm/packages` + }) + viaTool.statusCode.should.equal(200) + viaTool.json().should.have.property(`@flowfuse-${app.team.hashid}/one`) + }) + + it('platform_list_team_git_tokens matches GET /api/v1/teams/:teamId/git/tokens', async function () { + const tool = findTool('platform_list_team_git_tokens') + const { viaTool } = await expectToolMatchesRoute(inject, tool, { teamId: app.team.hashid }, { + method: 'GET', + url: `/api/v1/teams/${app.team.hashid}/git/tokens` + }) + viaTool.statusCode.should.equal(200) + viaTool.json().tokens.should.be.an.Array().and.have.length(1) + viaTool.json().tokens[0].should.have.property('name', 'ci-token') + }) + + it('platform_list_library_entries matches GET /storage/library/:libraryId/', async function () { + const tool = findTool('platform_list_library_entries') + const { viaTool } = await expectToolMatchesRoute(inject, tool, { libraryId: app.team.hashid, path: '' }, { + method: 'GET', + url: `/storage/library/${app.team.hashid}/` + }) + viaTool.statusCode.should.equal(200) + viaTool.json().should.be.an.Array().and.have.length(1) + viaTool.json()[0].should.have.property('fn', 'smoke-flow') + }) +})