-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcircleci-mcp.ts
More file actions
284 lines (247 loc) Β· 9.79 KB
/
circleci-mcp.ts
File metadata and controls
284 lines (247 loc) Β· 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
* Vigil + CircleCI MCP Server Integration
*
* Wraps CircleCI's MCP server (@circleci/mcp-server-circleci) with Vigil
* safety checks. Prevents AI agents from dangerous CI/CD operations like
* force-pushing to main, skipping tests, or accessing production secrets.
*
* Why this matters:
* CircleCI's MCP server exposes your entire CI/CD pipeline to AI agents.
* Agents can trigger builds, read logs, modify configs, and access secrets.
* Without guardrails, a single hallucinated tool call could:
* - Deploy untested code to production
* - Expose environment secrets in logs
* - Trigger cascading pipeline failures
* - Skip required security scans
*
* Setup:
* 1. npm install vigil-agent-safety @circleci/mcp-server-circleci
* 2. Configure your CircleCI token (see circleci.com/docs)
* 3. Use this wrapper instead of the raw MCP server
*/
import { checkAction, configure, loadPolicy, type VigilResult, type VigilInput } from 'vigil-agent-safety';
// βββ Vigil Configuration βββββββββββββββββββββββββββββββββββββββββββ
// 'enforce' = block dangerous calls, 'warn' = log but allow
configure({ mode: 'enforce' });
// βββ CircleCI-Specific Safety Rules ββββββββββββββββββββββββββββββββ
/** Branches that should never be directly modified by agents */
const PROTECTED_BRANCHES = ['main', 'master', 'production', 'release', 'staging'];
/** Pipeline parameters agents should never set */
const FORBIDDEN_PARAMS = ['skip-tests', 'skip-security', 'force-deploy', 'bypass-approval'];
/** Environment variable name patterns that indicate secrets */
const SECRET_PATTERNS = [
/api[_-]?key/i,
/secret/i,
/token/i,
/password/i,
/private[_-]?key/i,
/credentials/i,
/aws[_-]?(access|secret)/i,
/database[_-]?url/i,
];
// βββ CircleCI MCP Tool Interceptors ββββββββββββββββββββββββββββββββ
interface CircleCIToolCall {
tool: string;
params: Record<string, unknown>;
agentId?: string;
}
interface GuardResult {
allowed: boolean;
reason?: string;
vigilResult: VigilResult;
}
/**
* Main guard function β validates any CircleCI MCP tool call
*/
function guardCircleCICall(call: CircleCIToolCall): GuardResult {
const { tool, params, agentId = 'ci-agent' } = call;
// Step 1: Run Vigil's built-in checks (SSRF, injection, exfiltration, etc.)
const vigilResult = checkAction({
agent: agentId,
tool,
params,
});
if (vigilResult.decision === 'BLOCK') {
return { allowed: false, reason: vigilResult.reason, vigilResult };
}
// Step 2: CircleCI-specific safety rules
const ciCheck = checkCircleCIRules(tool, params);
if (ciCheck) {
return {
allowed: false,
reason: ciCheck,
vigilResult: {
...vigilResult,
decision: 'BLOCK',
rule: 'destructive',
risk_level: 'critical',
reason: ciCheck,
},
};
}
return { allowed: true, vigilResult };
}
/**
* CircleCI-specific rule checks beyond Vigil's built-in rules
*/
function checkCircleCIRules(tool: string, params: Record<string, unknown>): string | null {
// Rule 1: Block pipeline triggers on protected branches without approval
if (tool === 'trigger_pipeline' || tool === 'circleci_trigger_pipeline') {
const branch = (params.branch as string) || '';
if (PROTECTED_BRANCHES.some(b => branch === b || branch.endsWith(`/${b}`))) {
return `Cannot trigger pipeline on protected branch '${branch}'. Use a feature branch and create a PR instead.`;
}
// Block forbidden pipeline parameters
const pipelineParams = (params.parameters as Record<string, unknown>) || {};
for (const forbidden of FORBIDDEN_PARAMS) {
if (forbidden in pipelineParams) {
return `Forbidden pipeline parameter '${forbidden}'. Safety checks cannot be skipped by agents.`;
}
}
}
// Rule 2: Block config modifications that disable security jobs
if (tool === 'update_config' || tool === 'circleci_update_config') {
const config = JSON.stringify(params).toLowerCase();
if (config.includes('skip') && (config.includes('security') || config.includes('scan'))) {
return 'Cannot modify config to skip security scans. Security jobs are required.';
}
if (config.includes('no_output_timeout') && config.includes('60m')) {
return 'Suspiciously long timeout detected. Could indicate crypto mining or resource abuse.';
}
}
// Rule 3: Block direct access to environment variable values
if (tool === 'get_env_var' || tool === 'circleci_get_env_var') {
const varName = (params.name as string) || '';
if (SECRET_PATTERNS.some(p => p.test(varName))) {
return `Cannot read secret environment variable '${varName}'. Agents should not access credentials directly.`;
}
}
// Rule 4: Block deletion of production-related resources
if (tool === 'delete_project' || tool === 'circleci_delete_project') {
return 'Agents cannot delete CircleCI projects. This requires human approval.';
}
// Rule 5: Block SSH access to running jobs
if (tool === 'rerun_with_ssh' || tool === 'circleci_rerun_job_with_ssh') {
return 'Agents cannot SSH into CI jobs. This is a security boundary.';
}
// Rule 6: Rate-limit pipeline triggers (prevent runaway loops)
if (tool === 'trigger_pipeline' || tool === 'circleci_trigger_pipeline') {
if (!checkRateLimit(params.project_slug as string)) {
return 'Pipeline trigger rate limit exceeded. Max 5 triggers per project per 10 minutes.';
}
}
return null; // All checks passed
}
// βββ Rate Limiting βββββββββββββββββββββββββββββββββββββββββββββββββ
const triggerLog: Map<string, number[]> = new Map();
const RATE_LIMIT = 5;
const RATE_WINDOW_MS = 10 * 60 * 1000; // 10 minutes
function checkRateLimit(projectSlug: string = 'unknown'): boolean {
const now = Date.now();
const timestamps = triggerLog.get(projectSlug) || [];
const recent = timestamps.filter(t => now - t < RATE_WINDOW_MS);
if (recent.length >= RATE_LIMIT) {
return false;
}
recent.push(now);
triggerLog.set(projectSlug, recent);
return true;
}
// βββ MCP Wrapper βββββββββββββββββββββββββββββββββββββββββββββββββββ
type MCPHandler = (params: Record<string, unknown>) => Promise<unknown>;
/**
* Wrap any CircleCI MCP tool handler with Vigil safety
*
* @example
* ```ts
* const safeTrigger = withCIGuard('trigger_pipeline', originalHandler, 'coding-agent');
* const result = await safeTrigger({ branch: 'feat/new-ui', project_slug: 'gh/org/repo' });
* ```
*/
function withCIGuard(toolName: string, handler: MCPHandler, agentId?: string): MCPHandler {
return async (params: Record<string, unknown>) => {
const { allowed, reason, vigilResult } = guardCircleCICall({
tool: toolName,
params,
agentId,
});
if (!allowed) {
console.error(
`[vigil:circleci] π« BLOCKED ${toolName}: ${reason} (${vigilResult.latencyMs}ms)`
);
throw new Error(`[vigil] Blocked: ${reason}`);
}
if (vigilResult.decision === 'ESCALATE') {
console.warn(
`[vigil:circleci] β οΈ ESCALATED ${toolName}: ${vigilResult.reason}`
);
}
console.log(
`[vigil:circleci] β
${toolName} (${vigilResult.latencyMs}ms)`
);
return handler(params);
};
}
// βββ Usage Example βββββββββββββββββββββββββββββββββββββββββββββββββ
/*
* Full integration with a CircleCI MCP server:
*
* ```ts
* import { Server } from '@modelcontextprotocol/sdk/server/index.js';
* import { withCIGuard } from './circleci-mcp.js';
*
* const server = new Server({ name: 'circleci-vigil', version: '1.0.0' });
*
* // Original CircleCI tool handlers
* const circleCITools = {
* trigger_pipeline: async (params) => { ... },
* get_build_logs: async (params) => { ... },
* get_env_var: async (params) => { ... },
* rerun_with_ssh: async (params) => { ... },
* };
*
* // Wrap ALL tools with Vigil safety
* const safeTools = Object.fromEntries(
* Object.entries(circleCITools).map(([name, handler]) => [
* name,
* withCIGuard(name, handler, 'my-coding-agent'),
* ])
* );
*
* // Register safe tools with MCP server
* server.setRequestHandler(CallToolRequestSchema, async (request) => {
* const { name, arguments: args } = request.params;
* const tool = safeTools[name];
* if (!tool) throw new Error(`Unknown tool: ${name}`);
* return { content: [{ type: 'text', text: JSON.stringify(await tool(args)) }] };
* });
* ```
*
* What gets blocked:
*
* β trigger_pipeline({ branch: 'main' })
* β "Cannot trigger pipeline on protected branch 'main'"
*
* β trigger_pipeline({ parameters: { 'skip-tests': true } })
* β "Forbidden pipeline parameter 'skip-tests'"
*
* β get_env_var({ name: 'AWS_SECRET_ACCESS_KEY' })
* β "Cannot read secret environment variable"
*
* β rerun_with_ssh({ job_id: '...' })
* β "Agents cannot SSH into CI jobs"
*
* β delete_project({ project_slug: '...' })
* β "Agents cannot delete CircleCI projects"
*
* β 6th trigger_pipeline in 10 min
* β "Pipeline trigger rate limit exceeded"
*
* What gets allowed:
*
* β trigger_pipeline({ branch: 'feat/new-ui', project_slug: 'gh/org/repo' })
* β get_build_logs({ job_id: '...' })
* β get_env_var({ name: 'NODE_VERSION' })
* β get_pipeline_status({ pipeline_id: '...' })
*/
export { guardCircleCICall, withCIGuard, PROTECTED_BRANCHES, FORBIDDEN_PARAMS };