Skip to content

Commit b26c477

Browse files
authored
Add management-scoped API keys and a management CLI
Adds a management-scoped credential and an amcp management CLI so users and connected agents can run their whole AnythingMCP instance from the terminal. - McpApiKeyScope on McpApiKey (MCP | MANAGEMENT_READ | MANAGEMENT_ADMIN) + migration; a scope is a downward cap, always still limited by the owner's role. - JwtOrManagementKeyGuard: a drop-in for AuthGuard('jwt') on the management controllers that also accepts a management key, with a per-key rate limit. - CLI: generic 'amcp api <METHOD> <path>', 'amcp login --management', and 'amcp login --browser' (loopback; mints a key via the dashboard session, no backend auth change). - Dashboard: a Management API keys section to mint/revoke keys with a scope. - OpenAPI: File Search controllers annotated; a generated operation catalogue powers 'amcp api --list' with a CI freshness check. - Package made publishable (@anythingmcp/cli, public) + a release-triggered publish workflow. Relates to #1507.
1 parent e8f126c commit b26c477

43 files changed

Lines changed: 4082 additions & 87 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,12 @@ jobs:
7474
- name: Verify generated AI documentation is up to date
7575
run: node scripts/generate-llms-txt.mjs --check
7676

77+
# The amcp CLI's catalogue of management operations is generated from the
78+
# controllers guarded by JwtOrManagementKeyGuard. A new management route
79+
# must not ship without the CLI (and `amcp api --list`) knowing about it.
80+
- name: Verify the CLI management operation catalogue is up to date
81+
run: node scripts/generate-cli-operations.mjs --check
82+
7783
# The Docker image ships only hoisted dependencies; a nested one passes
7884
# every test here and then crashes the container (see the script).
7985
- name: Verify no backend dependency is nested out of the image

‎.github/workflows/publish-cli.yml‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Publish @anythingmcp/cli to npm as a public package.
2+
#
3+
# Trigger: a GitHub Release whose tag starts with "cli-v" (e.g. cli-v0.1.0).
4+
# The release tag's version is only a label here — the version actually
5+
# published is the one in packages/cli/package.json, so bump that in a PR first.
6+
#
7+
# One-time setup (owner):
8+
# 1. Create the npm org/scope "anythingmcp" (npmjs.com → Add Organization),
9+
# so the scoped name @anythingmcp/cli can be published.
10+
# 2. Create an npm "Automation" access token with publish rights.
11+
# 3. Add it as the repository secret NPM_TOKEN
12+
# (GitHub → Settings → Secrets and variables → Actions → New secret).
13+
# After that, publishing is just: create a Release tagged cli-v<version>.
14+
name: Publish CLI
15+
16+
on:
17+
release:
18+
types: [published]
19+
20+
jobs:
21+
publish:
22+
# Only CLI releases; other releases (if any) are ignored.
23+
if: startsWith(github.event.release.tag_name, 'cli-v')
24+
runs-on: ubuntu-latest
25+
permissions:
26+
contents: read
27+
id-token: write # npm provenance (public repo)
28+
steps:
29+
- uses: actions/checkout@v6
30+
- uses: actions/setup-node@v6
31+
with:
32+
node-version: 22
33+
registry-url: https://registry.npmjs.org
34+
- run: npm ci
35+
- run: npm run build -w packages/cli
36+
# publishConfig.access=public is set in packages/cli/package.json.
37+
- run: npm publish --provenance -w packages/cli
38+
env:
39+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
-- CreateEnum
2+
CREATE TYPE "McpApiKeyScope" AS ENUM ('MCP', 'MANAGEMENT_READ', 'MANAGEMENT_ADMIN');
3+
4+
-- AlterTable
5+
ALTER TABLE "mcp_api_keys" ADD COLUMN "scope" "McpApiKeyScope" NOT NULL DEFAULT 'MCP';

‎packages/backend/prisma/schema.prisma‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,11 @@ model McpApiKey {
384384
mcpServer McpServerConfig? @relation(fields: [mcpServerId], references: [id], onDelete: SetNull)
385385
key String @unique
386386
name String // label: "Claude Desktop", "Cursor", etc.
387+
// What the key may reach. MCP: tool calls on /mcp only (the historical
388+
// behaviour, and the default so existing keys keep it). MANAGEMENT_READ /
389+
// MANAGEMENT_ADMIN: the /api/* management surface (CLI), read-only or full,
390+
// always still capped by the owner's role.
391+
scope McpApiKeyScope @default(MCP)
387392
isActive Boolean @default(true) @map("is_active")
388393
lastUsedAt DateTime? @map("last_used_at")
389394
createdAt DateTime @default(now()) @map("created_at")
@@ -392,6 +397,12 @@ model McpApiKey {
392397
@@map("mcp_api_keys")
393398
}
394399

400+
enum McpApiKeyScope {
401+
MCP
402+
MANAGEMENT_READ
403+
MANAGEMENT_ADMIN
404+
}
405+
395406
// ── Connector Engine ────────────────────────────────────────────────────────
396407

397408
enum ConnectorType {

‎packages/backend/src/adapters/adapters.controller.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
1818
import { SkipThrottle } from '@nestjs/throttler';
1919
import type { Response } from 'express';
20-
import { AuthGuard } from '@nestjs/passport';
20+
import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard';
2121
import { AdaptersService } from './adapters.service';
2222
import { LicenseGuardService } from '../license/license-guard.service';
2323
import { McpServersService } from '../mcp-servers/mcp-servers.service';
@@ -118,7 +118,7 @@ export class AdaptersPublicController {
118118
// Authenticated endpoints
119119
@ApiTags('Adapters')
120120
@ApiBearerAuth()
121-
@UseGuards(AuthGuard('jwt'))
121+
@UseGuards(JwtOrManagementKeyGuard)
122122
@Controller('api/adapters')
123123
export class AdaptersController {
124124
constructor(

‎packages/backend/src/adapters/setup-links.controller.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
UnauthorizedException,
1010
UseGuards,
1111
} from '@nestjs/common';
12-
import { AuthGuard } from '@nestjs/passport';
12+
import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard';
1313
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
1414
import { Throttle } from '@nestjs/throttler';
1515
import type { Request } from 'express';
@@ -37,7 +37,7 @@ export class SetupLinksController {
3737
@Post('resolve')
3838
@HttpCode(200)
3939
@ApiBearerAuth()
40-
@UseGuards(AuthGuard('jwt'))
40+
@UseGuards(JwtOrManagementKeyGuard)
4141
@Throttle({ default: { limit: 20, ttl: 60_000 } })
4242
@ApiOperation({ summary: 'Open a connector setup link with the dashboard session' })
4343
async resolve(

‎packages/backend/src/alerts/alerts.controller.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Body, Controller, Delete, Get, Post, Put, Req, UseGuards } from '@nestjs/common';
22
import { ApiBearerAuth, ApiOperation, ApiProperty, ApiPropertyOptional, ApiTags } from '@nestjs/swagger';
3-
import { AuthGuard } from '@nestjs/passport';
3+
import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard';
44
import { Throttle } from '@nestjs/throttler';
55
import { IsBoolean, IsIn, IsInt, IsOptional, IsString, IsUrl, Max, MaxLength, Min } from 'class-validator';
66
import { Roles, RolesGuard } from '../auth/roles.guard';
@@ -54,7 +54,7 @@ class SaveAlertWebhookDto {
5454

5555
@ApiTags('Alerts')
5656
@ApiBearerAuth()
57-
@UseGuards(AuthGuard('jwt'), RolesGuard)
57+
@UseGuards(JwtOrManagementKeyGuard, RolesGuard)
5858
@Roles('ADMIN')
5959
@Controller('api/admin/settings')
6060
export class AlertsAdminController {

‎packages/backend/src/audit/audit.controller.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Controller, Get, Query, Req, UseGuards } from '@nestjs/common';
22
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
3-
import { AuthGuard } from '@nestjs/passport';
3+
import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard';
44
import { AuditService } from './audit.service';
55
import {
66
ANALYTICS_DEFAULT_DAYS,
@@ -10,7 +10,7 @@ import {
1010

1111
@ApiTags('Audit')
1212
@ApiBearerAuth()
13-
@UseGuards(AuthGuard('jwt'))
13+
@UseGuards(JwtOrManagementKeyGuard)
1414
@Controller('api/audit')
1515
export class AuditController {
1616
constructor(private readonly auditService: AuditService) {}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { ExecutionContext, ForbiddenException, HttpException, UnauthorizedException } from '@nestjs/common';
2+
import { PrismaService } from '../common/prisma.service';
3+
import { JwtOrManagementKeyGuard } from './jwt-or-management-key.guard';
4+
5+
/**
6+
* Integration test for the management-key path of the guard, against a real
7+
* database. The JWT fallback (no key presented) is Passport's unchanged
8+
* behaviour and is not exercised here.
9+
*/
10+
const prisma = new PrismaService();
11+
// Redis not connected → the per-key rate limit falls open (not under test here).
12+
const noRedis = { isConnected: false } as never;
13+
const guard = new JwtOrManagementKeyGuard(prisma as never, noRedis);
14+
15+
const TAG = `mgmtcli-test-${Date.now()}`;
16+
const orgId = `${TAG}-org`;
17+
const adminId = `${TAG}-admin`;
18+
const memberId = `${TAG}-member`;
19+
20+
const keys = {
21+
mcp: `mcp_${'a'.repeat(40)}${Date.now()}`,
22+
read: `mcp_${'b'.repeat(40)}${Date.now()}`,
23+
admin: `mcp_${'c'.repeat(40)}${Date.now()}`,
24+
memberAdminScope: `mcp_${'d'.repeat(40)}${Date.now()}`,
25+
inactive: `mcp_${'e'.repeat(40)}${Date.now()}`,
26+
};
27+
28+
function contextFor(key: string | undefined, method: string): { ctx: ExecutionContext; req: Record<string, unknown> } {
29+
const req: Record<string, unknown> = {
30+
method,
31+
headers: key ? { authorization: `Bearer ${key}` } : {},
32+
};
33+
const ctx = {
34+
switchToHttp: () => ({ getRequest: () => req }),
35+
} as unknown as ExecutionContext;
36+
return { ctx, req };
37+
}
38+
39+
beforeAll(async () => {
40+
await prisma.$connect();
41+
await prisma.organization.create({ data: { id: orgId, name: TAG } });
42+
await prisma.user.create({
43+
data: { id: adminId, email: `${TAG}[email protected]`, role: 'ADMIN', organizationId: orgId },
44+
});
45+
await prisma.user.create({
46+
data: { id: memberId, email: `${TAG}[email protected]`, role: 'VIEWER', organizationId: orgId },
47+
});
48+
await prisma.organizationMember.create({ data: { userId: adminId, organizationId: orgId, role: 'ADMIN' } });
49+
await prisma.organizationMember.create({ data: { userId: memberId, organizationId: orgId, role: 'VIEWER' } });
50+
51+
const mk = (key: string, userId: string, scope: 'MCP' | 'MANAGEMENT_READ' | 'MANAGEMENT_ADMIN', isActive = true) =>
52+
prisma.mcpApiKey.create({ data: { key, name: key.slice(0, 12), userId, organizationId: orgId, scope, isActive } });
53+
await mk(keys.mcp, adminId, 'MCP');
54+
await mk(keys.read, adminId, 'MANAGEMENT_READ');
55+
await mk(keys.admin, adminId, 'MANAGEMENT_ADMIN');
56+
await mk(keys.memberAdminScope, memberId, 'MANAGEMENT_ADMIN');
57+
await mk(keys.inactive, adminId, 'MANAGEMENT_ADMIN', false);
58+
});
59+
60+
afterAll(async () => {
61+
await prisma.mcpApiKey.deleteMany({ where: { organizationId: orgId } });
62+
await prisma.organizationMember.deleteMany({ where: { organizationId: orgId } });
63+
await prisma.user.deleteMany({ where: { organizationId: orgId } });
64+
await prisma.organization.deleteMany({ where: { id: orgId } });
65+
await prisma.$disconnect();
66+
});
67+
68+
describe('JwtOrManagementKeyGuard (management-key path)', () => {
69+
it('rejects an MCP-scoped key on the management API', async () => {
70+
const { ctx } = contextFor(keys.mcp, 'GET');
71+
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException);
72+
});
73+
74+
it('rejects an inactive key', async () => {
75+
const { ctx } = contextFor(keys.inactive, 'GET');
76+
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(UnauthorizedException);
77+
});
78+
79+
it('allows a MANAGEMENT_READ key on a GET and sets the user+role', async () => {
80+
const { ctx, req } = contextFor(keys.read, 'GET');
81+
await expect(guard.canActivate(ctx)).resolves.toBe(true);
82+
expect(req.user).toMatchObject({ sub: adminId, role: 'ADMIN', organizationId: orgId });
83+
expect(req.mcpKeyScope).toBe('MANAGEMENT_READ');
84+
});
85+
86+
it('forbids a MANAGEMENT_READ key on a non-safe method', async () => {
87+
const { ctx } = contextFor(keys.read, 'POST');
88+
await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
89+
});
90+
91+
it('allows a MANAGEMENT_ADMIN key on a POST', async () => {
92+
const { ctx, req } = contextFor(keys.admin, 'POST');
93+
await expect(guard.canActivate(ctx)).resolves.toBe(true);
94+
expect(req.user).toMatchObject({ sub: adminId, role: 'ADMIN' });
95+
});
96+
97+
it('carries a non-admin owner role even with an admin-scope key (RolesGuard will cap it)', async () => {
98+
const { ctx, req } = contextFor(keys.memberAdminScope, 'POST');
99+
await expect(guard.canActivate(ctx)).resolves.toBe(true);
100+
expect((req.user as { role: string }).role).toBe('VIEWER');
101+
});
102+
103+
it('accepts the key via the X-API-Key header too', async () => {
104+
const req: Record<string, unknown> = { method: 'GET', headers: { 'x-api-key': keys.read } };
105+
const ctx = { switchToHttp: () => ({ getRequest: () => req }) } as unknown as ExecutionContext;
106+
await expect(guard.canActivate(ctx)).resolves.toBe(true);
107+
});
108+
109+
it('rate-limits a key once Redis is connected and the per-minute ceiling is exceeded', async () => {
110+
const counts = new Map<string, number>();
111+
const fakeRedis = {
112+
isConnected: true,
113+
incr: async (k: string) => { const n = (counts.get(k) ?? 0) + 1; counts.set(k, n); return n; },
114+
expire: async () => undefined,
115+
ttl: async () => 60,
116+
} as never;
117+
const previous = process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE;
118+
process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE = '2';
119+
try {
120+
const limited = new JwtOrManagementKeyGuard(prisma as never, fakeRedis);
121+
const call = () => limited.canActivate(contextFor(keys.admin, 'GET').ctx);
122+
await expect(call()).resolves.toBe(true);
123+
await expect(call()).resolves.toBe(true);
124+
let thrown: unknown;
125+
try { await call(); } catch (error) { thrown = error; }
126+
expect(thrown).toBeInstanceOf(HttpException);
127+
expect((thrown as HttpException).getStatus()).toBe(429);
128+
} finally {
129+
if (previous === undefined) delete process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE;
130+
else process.env.MANAGEMENT_RATE_LIMIT_PER_MINUTE = previous;
131+
}
132+
});
133+
});

0 commit comments

Comments
 (0)