Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 7x 7x 7x 7x 7x 7x 7x 7x 7x 17x 5x 5x 1x 4x 4x 4x 4x 4x 2x 2x 2x 3x 3x 106x 3x 2x 2x 2x 1x 3x 5x 9x 2x 17x 15x 15x 15x 15x 1x 1x 6x 4x 2x 2x 2x 2x 1x 1x 2x 2x 1x 1x 2x 2x 1x 1x 2x 2x 1x 1x 12x 12x 12x 12x 6x 6x 6x 2x 1x 1x 1x 1x 4x 2x 1x 1x 1x 1x 4x 4x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 17x 1x | import * as z from 'zod';
import { BrowseRunnersSchema } from './schema-readonly';
import { ManageRunnerSchema } from './schema';
import { ToolRegistry, EnhancedToolDefinition } from '../../types';
import { assertActionAllowed, GITLAB_MAX_PER_PAGE } from '../utils';
import { ConnectionManager } from '../../services/ConnectionManager';
import { cleanGidsFromObject } from '../../utils/idConversion';
import { getGitLabApiUrlFromContext } from '../../oauth/token-context';
import { gitlab, toQuery } from '../../utils/gitlab-api';
import { graphqlSupports } from '../instance-version';
import {
LIST_RUNNERS,
LIST_OWNED_RUNNERS,
LIST_GROUP_RUNNERS,
LIST_PROJECT_RUNNERS,
GET_RUNNER,
LIST_RUNNER_JOBS,
RESOLVE_GROUP_ID,
RESOLVE_PROJECT_ID,
RUNNER_CREATE,
RUNNER_UPDATE,
RUNNER_DELETE,
type RunnerListVars,
} from '../../graphql/runners';
/**
* Runners tools registry - 2 CQRS tools
*
* browse_runners (Query): list_all, list_owned, list_project, list_group, get, list_jobs
* manage_runner (Command): create_authentication_token, update, pause, resume, delete,
* reset_authentication_token
*
* Backed by the GitLab GraphQL runner API. pause/resume map to runnerUpdate(paused).
* Per-runner token reset has no GraphQL mutation, so reset_authentication_token uses
* the REST endpoint. Gated behind USE_RUNNERS. Free tier (writes require the
* create_runner / manage_runner scope; list_all needs admin).
*/
const runnerGid = (id: number): string => `gid://gitlab/Ci::Runner/${id}`;
/** Build the shared GraphQL list filter variables from the parsed input. */
function listVars(input: {
type?: string;
status?: string;
paused?: boolean;
tag_list?: string[];
search?: string;
first?: number;
after?: string;
}): RunnerListVars {
return {
type: input.type ?? null,
status: input.status ?? null,
paused: input.paused ?? null,
tagList: input.tag_list ?? null,
search: input.search ?? null,
first: input.first ?? 20,
after: input.after ?? null,
};
}
interface RunnerSettingsInput {
description?: string | null;
paused?: boolean | null;
locked?: boolean | null;
runUntagged?: boolean | null;
tagList?: string[] | null;
accessLevel?: string | null;
maximumTimeout?: number | null;
maintenanceNote?: string | null;
}
/** Map provided snake_case settings onto a camelCase mutation input (omitting absent ones). */
function applyRunnerSettings(
target: RunnerSettingsInput,
src: {
description?: string;
paused?: boolean;
locked?: boolean;
run_untagged?: boolean;
tag_list?: string[];
access_level?: string;
maximum_timeout?: number;
maintenance_note?: string;
},
): void {
if (src.description !== undefined) target.description = src.description;
Iif (src.paused !== undefined) target.paused = src.paused;
Iif (src.locked !== undefined) target.locked = src.locked;
if (src.run_untagged !== undefined) target.runUntagged = src.run_untagged;
if (src.tag_list !== undefined) target.tagList = src.tag_list;
Iif (src.access_level !== undefined) target.accessLevel = src.access_level;
if (src.maximum_timeout !== undefined) target.maximumTimeout = src.maximum_timeout;
Iif (src.maintenance_note !== undefined) target.maintenanceNote = src.maintenance_note;
}
const RestRunnersSchema = z.array(
z.object({
id: z.number(),
description: z.string().nullable(),
runner_type: z.string(),
status: z.string().nullable(),
paused: z.boolean(),
}),
);
interface OwnedRunnerFilters {
type?: string;
status?: string;
paused?: boolean;
tag_list?: string[];
}
/** One validated page of GET /runners with the server-side filters applied. */
async function fetchOwnedRunnersPage(filters: OwnedRunnerFilters, perPage: number, page: number) {
const parsed = RestRunnersSchema.safeParse(
await gitlab.get('runners', {
query: toQuery({
type: filters.type?.toLowerCase(),
status: filters.status?.toLowerCase(),
paused: filters.paused,
tag_list: filters.tag_list?.join(','),
per_page: perPage,
page,
}),
}),
);
if (!parsed.success) {
throw new Error(
`GitLab API error: unexpected runners response (${parsed.error.issues[0]?.message ?? 'invalid'})`,
);
}
return parsed.data;
}
/**
* The current user's runners through REST, shaped like the GraphQL connection,
* for instances without currentUser.runners (GitLab 18.3). REST pages by number,
* so the cursor is the next page number. REST has no `search`, so it is matched
* on the description before paginating: REST pages are walked until the
* requested page of matches is complete, and the cursor counts pages of matches.
* Fields the REST listing lacks are null.
*/
async function listOwnedRunnersViaRest(
input: OwnedRunnerFilters & { search?: string; first?: number; after?: string },
) {
const perPage = input.first ?? 20;
const page = Number(input.after) > 0 ? Number(input.after) : 1;
const search = input.search?.toLowerCase();
let runners: z.infer<typeof RestRunnersSchema>;
let hasNextPage: boolean;
if (search) {
const wanted = page * perPage;
const matches: typeof runners = [];
// One match beyond the requested page tells whether another page exists.
for (let restPage = 1; matches.length <= wanted; restPage++) {
const batch = await fetchOwnedRunnersPage(input, GITLAB_MAX_PER_PAGE, restPage);
for (const runner of batch) {
if ((runner.description ?? '').toLowerCase().includes(search)) matches.push(runner);
}
if (batch.length < GITLAB_MAX_PER_PAGE) break;
}
runners = matches.slice(wanted - perPage, wanted);
hasNextPage = matches.length > wanted;
} else {
runners = await fetchOwnedRunnersPage(input, perPage, page);
hasNextPage = runners.length === perPage;
}
return {
nodes: runners.map((r) => ({
id: r.id,
description: r.description,
runnerType: r.runner_type.toUpperCase(),
status: r.status?.toUpperCase() ?? null,
paused: r.paused,
locked: null,
runUntagged: null,
tagList: null,
accessLevel: null,
maximumTimeout: null,
jobExecutionStatus: null,
jobCount: null,
contactedAt: null,
createdAt: null,
})),
pageInfo: {
hasNextPage,
endCursor: hasNextPage ? String(page + 1) : null,
},
};
}
/** Throw on a non-empty GraphQL mutation `errors` array. */
function assertNoErrors(errors: string[] | undefined): void {
if (errors && errors.length > 0) {
throw new Error(`GitLab API error: ${errors.join(', ')}`);
}
}
export const runnersToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
// ============================================================================
// browse_runners - CQRS Query Tool (discriminated union schema)
// ============================================================================
[
'browse_runners',
{
name: 'browse_runners',
description:
"Inspect CI runners. Actions: list_all (every runner on the instance - admin), list_owned (the current user's runners), list_project / list_group (runners available to a project/group), get (single runner by ID), list_jobs (jobs a runner has executed). Related: manage_runner to register, update, pause/resume, or delete runners.",
inputSchema: z.toJSONSchema(BrowseRunnersSchema),
requirements: { default: { tier: 'free' } },
gate: { envVar: 'USE_RUNNERS', defaultValue: true },
handler: async (args: unknown): Promise<unknown> => {
const input = BrowseRunnersSchema.parse(args);
assertActionAllowed('browse_runners', input.action);
const client = ConnectionManager.getInstance().getClient(getGitLabApiUrlFromContext());
switch (input.action) {
case 'list_all': {
const res = await client.request(LIST_RUNNERS, listVars(input));
return cleanGidsFromObject(res.runners);
}
case 'list_owned': {
if (!graphqlSupports('CurrentUser', 'runners')) {
return listOwnedRunnersViaRest(input);
}
const res = await client.request(LIST_OWNED_RUNNERS, listVars(input));
return cleanGidsFromObject(res.currentUser?.runners ?? { nodes: [] });
}
case 'list_project': {
const res = await client.request(LIST_PROJECT_RUNNERS, {
fullPath: input.project_id,
...listVars(input),
});
if (!res.project) {
throw new Error(`Project "${input.project_id}" not found or not accessible`);
}
return cleanGidsFromObject(res.project.runners);
}
case 'list_group': {
const res = await client.request(LIST_GROUP_RUNNERS, {
fullPath: input.group_id,
...listVars(input),
});
if (!res.group) {
throw new Error(`Group "${input.group_id}" not found or not accessible`);
}
return cleanGidsFromObject(res.group.runners);
}
case 'get': {
const res = await client.request(GET_RUNNER, { id: runnerGid(input.runner_id) });
if (!res.runner) {
throw new Error(`Runner ${input.runner_id} not found`);
}
return cleanGidsFromObject(res.runner);
}
case 'list_jobs': {
const res = await client.request(LIST_RUNNER_JOBS, {
id: runnerGid(input.runner_id),
statuses: input.statuses ?? null,
first: input.first ?? 20,
after: input.after ?? null,
});
if (!res.runner) {
throw new Error(`Runner ${input.runner_id} not found`);
}
return cleanGidsFromObject(res.runner.jobs ?? { nodes: [] });
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// ============================================================================
// manage_runner - CQRS Command Tool (discriminated union schema)
// ============================================================================
[
'manage_runner',
{
name: 'manage_runner',
description:
'Register and control CI runners. Actions: create_authentication_token (register a runner, GitLab 16+, returns a one-time token), update (settings), pause/resume (toggle job pickup), delete, reset_authentication_token (rotate the token). Related: browse_runners to discover runners.',
inputSchema: z.toJSONSchema(ManageRunnerSchema),
requirements: { default: { tier: 'free' } },
gate: { envVar: 'USE_RUNNERS', defaultValue: true },
handler: async (args: unknown): Promise<unknown> => {
const input = ManageRunnerSchema.parse(args);
assertActionAllowed('manage_runner', input.action);
const client = ConnectionManager.getInstance().getClient(getGitLabApiUrlFromContext());
switch (input.action) {
case 'create_authentication_token': {
const createInput: {
runnerType: string;
groupId?: string;
projectId?: string;
} & RunnerSettingsInput = { runnerType: input.runner_type };
applyRunnerSettings(createInput, input);
if (input.runner_type === 'GROUP_TYPE') {
if (!input.group_id) {
throw new Error('group_id is required for a GROUP_TYPE runner');
}
const g = await client.request(RESOLVE_GROUP_ID, { fullPath: input.group_id });
Iif (!g.group) throw new Error(`Group "${input.group_id}" not found`);
createInput.groupId = g.group.id;
} else if (input.runner_type === 'PROJECT_TYPE') {
if (!input.project_id) {
throw new Error('project_id is required for a PROJECT_TYPE runner');
}
const p = await client.request(RESOLVE_PROJECT_ID, { fullPath: input.project_id });
Iif (!p.project) throw new Error(`Project "${input.project_id}" not found`);
createInput.projectId = p.project.id;
}
const res = await client.request(RUNNER_CREATE, { input: createInput });
assertNoErrors(res.runnerCreate?.errors);
return cleanGidsFromObject(res.runnerCreate?.runner);
}
case 'update': {
const updateInput: { id: string } & RunnerSettingsInput = {
id: runnerGid(input.runner_id),
};
applyRunnerSettings(updateInput, input);
const res = await client.request(RUNNER_UPDATE, { input: updateInput });
assertNoErrors(res.runnerUpdate?.errors);
return cleanGidsFromObject(res.runnerUpdate?.runner);
}
case 'pause':
case 'resume': {
const res = await client.request(RUNNER_UPDATE, {
input: { id: runnerGid(input.runner_id), paused: input.action === 'pause' },
});
assertNoErrors(res.runnerUpdate?.errors);
return cleanGidsFromObject(res.runnerUpdate?.runner);
}
case 'delete': {
const res = await client.request(RUNNER_DELETE, {
input: { id: runnerGid(input.runner_id) },
});
assertNoErrors(res.runnerDelete?.errors);
return { deleted: true, runner_id: input.runner_id };
}
case 'reset_authentication_token': {
// No GraphQL mutation for per-runner token reset; use the REST endpoint.
return gitlab.post(`runners/${input.runner_id}/reset_authentication_token`, {
contentType: 'json',
});
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
]);
/**
* Get read-only tool names from the registry
*/
export function getRunnersReadOnlyToolNames(): string[] {
return ['browse_runners'];
}
|