Skip to main content
Glama
README.md
# ado-mcp

An MCP (Model Context Protocol) server that gives an AI agent a small, guarded set of Azure DevOps operations, plus the host-side scripts that let that agent work in Azure DevOps as its own identity instead of as you.

## Why an agent identity

An agent that works tickets and opens pull requests should not do it with your credentials. If it does, every comment, push and vote looks like yours, and nothing stops it from approving its own work. This repository sets up a different arrangement:

- **The agent is its own Entra service principal.** In Azure DevOps its commits, pull requests and comments are authored by the service principal, not by the human.
- **It cannot approve or complete its own work.** Branch policies (step 3) require a human reviewer and block the last pusher and the requester from approving, so the service principal's vote does not count. Deny entries (step 1) remove its right to complete a pull request, bypass policies, force push or push to `main`, and the pull request tools in this server expose no vote, approve, complete or auto-complete operation. The negative test matrix (step 4) tries each of these as the service principal and fails if any succeeds.
- **The human approves and completes.** The agent opens the pull request; a person reviews it and completes it in the portal.
- **There is no long-lived PAT.** A certificate held in Key Vault mints a short-lived Entra token on demand. A Claude Code `PreToolUse` hook (`host/ado-token-hook.mjs`) asks the server whether its token is still good and, only when it is not, runs `host/ado-token-push.ps1`, which writes a fresh token file into the container's tmpfs. The server (`ADO_AUTH_MODE=token-file`) reads that file, checks the audience, expiry, client, tenant and identity claims, and locks if anything is wrong. No PAT is allowed in its environment.
- **Git pushes go out as the service principal too.** `host/git-credential-ado-sp.ps1` is a git credential helper that answers with a bearer token, and a per-worktree identity (`host/agent-worktree-post-checkout`, installed by `host/Install-AgentAdoIdentity.ps1`) applies it only to linked worktrees under `.claude/worktrees/`. Your own checkouts and shells keep your identity.
- **One hook guards the edges.** `host/comment-owner-guard.mjs` blocks an agent from posting a comment as the human on a repository or project the human does not own (GitHub owner match, or direct membership in the Azure DevOps project's Project Administrators group). It guards comment posts only; it never blocks a push, a pull request or any other action.

Everything else in this file is either how to set that up, or reference for the MCP server itself.

### PAT mode, for trying the server

You can run the server with a personal access token instead (`AZURE_DEVOPS_EXT_PAT`, see Running locally). PAT mode exists so you can try the tools without any Entra setup. In PAT mode there is no separate identity: wherever this document says "service principal" (for example, "comments written by the configured service principal"), read it as the PAT owner. None of the approval protections above exist in PAT mode; they come from the service principal, the deny entries and the branch policies.

## Setup

### Prerequisites

- An Azure DevOps organization backed by Microsoft Entra ID, and a person who can add users, set repository permissions and branch policies, and revoke their own PAT (the "owner" below).
- A **service principal** (an app registration plus its enterprise application) in the same tenant. Note its tenant id, its application (client) id, and its enterprise application object id. Its Azure DevOps user id is a different GUID (not the object id and not the client id); step 2 resolves it live and refuses to continue on a mismatch, and you pass it as `ADO_SP_USER_ID` to the scripts.
- A **certificate** registered on that app, exportable, installed in `Cert:\CurrentUser\My` on the owner's machine. `host/admin/Publish-AdoSpCertificate.ps1` uploads it to Key Vault as a base64 PKCS#12 secret.
- An **Azure Key Vault** with that secret. The owner needs Key Vault Secrets Officer to upload it; each person or machine that runs the token push needs Key Vault Secrets User and an `az login` of their own.
- On the host: PowerShell 7, the Azure CLI (`az`), Docker, Node.js 22 or newer, git 2.46 or newer (the credential helper uses the `authtype` credential protocol), and Claude Code (the on-demand token refresh is a Claude Code hook). The admin scripts are written for Windows; `host/Install-AdoTokenOnDemand.ps1` also runs on macOS.
- A **sandbox repository** in a project the service principal can reach, with `sp-sandbox` in its name. The negative matrix writes only there.

The portal-side detail (what to check by eye, rollback per step) is in `host/admin/README.md`.

### Settings

No script carries an organization, tenant, GUID, project or person. Each value comes from a parameter or an environment variable, and a script stops with `config_missing:<VARIABLE>` or `config_invalid:<VARIABLE>` if it has neither.

| Setting | Environment variable | Used by |
| --- | --- | --- |
| Entra tenant id | `ADO_SP_TENANT_ID` | all host scripts |
| Service principal application (client) id | `ADO_SP_CLIENT_ID` | all host scripts |
| Service principal Azure DevOps user id | `ADO_SP_USER_ID` | all host scripts |
| Organization URL, `https://dev.azure.com/<organization>` | `ADO_ORG_URL` | all host scripts |
| Key Vault name | `ADO_SP_VAULT_NAME` | token mint (`host/AdoSpToken.psm1`) |
| Key Vault secret name | `ADO_SP_SECRET_NAME` | token mint (`host/AdoSpToken.psm1`) |
| Expected client id, tenant id and identity | `ADO_EXPECTED_CLIENT_ID`, `ADO_EXPECTED_TENANT_ID`, `ADO_EXPECTED_IDENTITY` | `compose.token-file.yaml` (no defaults; compose refuses to start without them). Step 2 sets them from the values above. |
| Project name, project id, iteration root | `ADO_PROJECT_NAME`, `ADO_PROJECT_ID`, `ADO_ITERATION_IS_ROOT` | scope pins; step 2 takes them as `-ProjectName`, `-ProjectId`, `-IterationIsRoot` |
| Directory holding the project registry | `ADO_MCP_HOME` | `compose.token-file.yaml`; step 2 sets it to `~/.ado-mcp` |
| Owner identity for the comment guard | `COMMENT_GUARD_GITHUB_OWNER`, `COMMENT_GUARD_OWNER_PRINCIPAL`, `COMMENT_GUARD_ORG_URL` | `host/comment-owner-guard.mjs` (all three required; with one missing, a command that needs an ownership decision is blocked) |
| Agent git identity | `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_NOSYSTEM=1` | agent sessions |

Parameters that have no environment variable and are mandatory where a script needs them: `-Projects`, `-SpObjectId`, `-OwnerUpn`, `-SandboxProject`, `-Project`, `-Repository`, `-AdoProject`, `-AgentName`, `-CheckProjects`. The numbered rollout scripts (steps 1 to 7) are a dry run (read-only GETs and a printed plan) until you add `-Apply`. Three scripts are not: `host/admin/Publish-AdoSpCertificate.ps1` writes to Key Vault immediately, `host/Install-AgentAdoIdentity.ps1` copies its files by default, and `host/Install-AdoTokenOnDemand.ps1` edits `settings.json`, rebuilds the container and pushes a token by default. Add `-WhatIf` to preview the last two.

### Steps 1 to 7

All live in `host/admin/`. Run them yourself, signed in as the owner with `az login`. Read the dry run, then add `-Apply`. Order: **1, 2, 4 (`-Layer Deny`), 3, 4 (`-Layer Policy`), 6, 5.** Step 7 can come any time after 2.

| Step | Script | What it does |
| --- | --- | --- |
| 1 | `host/admin/1-Grant-AdoAgentIdentity.ps1` | Adds the service principal to the organization (Basic) and as Contributor in each project, then writes deny entries: bypass policies, force push, create tag, edit policies, manage permissions, and more at project scope, and Contribute on `refs/heads/main` of every repo. Reads everything back. |
| 2 | `host/admin/2-Invoke-AdoSpCutover.ps1` | Runs `host/Install-AgentAdoIdentity.ps1` and `host/Install-AdoTokenOnDemand.ps1`: installs the agent git identity files, registers the `PreToolUse` token hook, recreates the container from `compose.token-file.yaml` with no PAT, forces one token push, and checks the container's identity equals the service principal. `-PlanOnly` prints the plan offline. |
| 4 (Deny) | `host/admin/4-Test-AdoSpNegativeMatrix.ps1 -Layer Deny` | As the service principal, asks Azure DevOps whether each denied permission is really denied. With `-Apply`, also tries a push to `main` and a tag in the sandbox repo. |
| 3 | `host/admin/3-Set-AdoBranchPolicies.ps1` | Project-wide branch policies on `main` and `release/*`: minimum reviewers 1, the owner as required reviewer, creator and last-pusher votes do not count, votes reset on new pushes. |
| 4 (Policy) | `host/admin/4-Test-AdoSpNegativeMatrix.ps1 -Layer Policy -Apply` | In the sandbox repo, the service principal opens a pull request and tries to complete it, set auto-complete and approve it itself. Every attempt must be refused. |
| 6 | `host/admin/6-Switch-OwnerGitToEntra.ps1` | Moves the owner's own git access from a PAT helper to Git Credential Manager (Entra). Do this before step 5. |
| 5 | `host/admin/5-Revoke-OwnerPat.ps1` | Last. Lists the owner's PATs and revokes one, only with `-ConfirmStep4Passed`. |
| 7 | `host/admin/7-Enable-AdoAgentRepo.ps1` | For shared projects: enables the service principal on one repo, main-branch deny first, then a repo-scoped allow, then repo-scoped policies. |

Other owner scripts: `host/admin/Publish-AdoSpCertificate.ps1` (upload the certificate to Key Vault), and `host/admin/Lock-AdoAgentFolder.ps1` with `host/admin/Unlock-AdoAgentFolder.ps1` (Windows: lock the installed `~/.claude/ado-agent` folder, which holds the agent's git identity files, so a non-elevated agent session cannot edit or replace them). Each documents itself in its header.

### Then, on the agent host

1. Install the hook into your Claude Code user configuration by hand: `host/comment-owner-guard.mjs` as a `PreToolUse` hook with matcher `Bash|PowerShell|mcp__plugin_github_github__.*` (see its header). Step 2 registers the token hook itself. Add this to `~/.claude/settings.json`, merging into any existing `hooks` and `env` keys:

   ```json
   {
     "env": {
       "COMMENT_GUARD_GITHUB_OWNER": "<your-github-login>",
       "COMMENT_GUARD_OWNER_PRINCIPAL": "<owner-email-or-principal>",
       "COMMENT_GUARD_ORG_URL": "https://dev.azure.com/<your-org>"
     },
     "hooks": {
       "PreToolUse": [
         {
           "matcher": "Bash|PowerShell|mcp__plugin_github_github__.*",
           "hooks": [
             {
               "type": "command",
               "command": "node <path-to-repo>/host/comment-owner-guard.mjs"
             }
           ]
         }
       ]
     }
   }
   ```

   The guard reads the hook's JSON from stdin and, to block, writes a message to stderr and exits 2 (also on any unexpected error); otherwise it exits 0. All three `COMMENT_GUARD_*` variables are required, with no defaults. A command that needs an ownership decision while one is missing is blocked. The `env` block sets them for the Claude Code process, and the hook inherits them.
2. Start agent sessions with `GIT_CONFIG_GLOBAL` pointing at the installed `agent.gitconfig`, or install the per-worktree identity with `host/Install-AgentAdoIdentity.ps1 -ApplyWorktreeIdentity`.
3. Register the server with Claude Code (see Registering with Claude Code below). In token-file mode the server serves several projects from the registry file; see Registry mode.

## The MCP server

It is pinned to **one organization and one project**: every tool call is checked against that scope, and anything outside it is refused rather than passed through. It speaks MCP over Streamable HTTP, written in Node.js (22 or newer) with two runtime dependencies (`@modelcontextprotocol/sdk` and `zod`).

## What it is for

An AI agent that works tickets usually needs to query items, move them across a board, comment, and create child tasks, but should not be able to wander into other projects, rewrite arbitrary fields, or approve its own pull requests. This server gives the agent exactly those operations, and each tool refuses what it should not do.

## Tools

All tools act only inside the configured organization and project. Items, parents, pull requests and repositories outside it are refused.

| Tool | What it does | What it is blocked from |
| --- | --- | --- |
| `ado_identity` | Returns the scope (organization, project, project id, iteration setting); `live: true` re-reads the project from ADO by id. | Read-only. |
| `ado_query` | Finds work items by filters or a raw WIQL string. | WIQL must contain a top-level `[System.TeamProject] = '<project>'` clause and no `OR`. Every fetched item is re-checked against the project. Capped at 200 rows and 20 extra fields. |
| `ado_get_item` | Fetches one item, optionally with relations and comments, plus QA comments from linked Test Cases. | Items outside the project. |
| `ado_move_ticket` | Moves an item to a state or board column. | Items outside the project. Moves the item under the required iteration if it is elsewhere. `completedWork` is written only when you pass it, never inferred. |
| `ado_comment` | Adds a comment (plain text, escaped). | Items outside the project. |
| `ado_edit_comment`, `ado_delete_comment` | Edit or delete a comment. | Only comments written by the configured service principal. |
| `ado_pr_get` | Reads a pull request's status, branches, head commit and thread counts. | Read-only. |
| `ado_pr_build` | Reports whether every pipeline's latest run for the PR head commit succeeded. | Read-only. "passed" only when proven; any error or missing run gives "not_passed". |
| `ado_pr_publish` | Flips a draft pull request to published. | Only active drafts created by the configured service principal. No vote, approve or complete exists in this server. |
| `ado_pr_link_work_item` | Links a pull request to a work item. | Both ends must be in the project. Idempotent; guarded by a revision test. |
| `ado_attach_file` | Uploads base64 content and attaches it to an item. | Scope is checked before the upload. |
| `ado_board_snapshot` | Columns, counts and items for a board of the default team. | Read-only. |
| `ado_create_task` | Creates a Task under a parent. | Parent must be in the project; area and iteration come from the resolved defaults; estimates are never defaulted. |
| `ado_create_work_item` | Creates an item of any type valid in the project. | Area must be in the team's areas (or anywhere in the project with `ADO_AREA_ANY_IN_PROJECT=1`); iteration must be under the project; `Custom.*` fields only for custom fields. |
| `ado_update_fields` | Updates explicitly typed fields (title, description, tags, estimates, area, iteration, and so on). | Cannot change state, board columns or the team project. Tag edits are verified against the response. |

### Description gates

Two checks run inside the code path that sends a patch, so no tool can bypass them:

- **Epic gate:** a write to an Epic's description is refused unless the HTML contains each of the sections Goal, In scope, Out of scope, Spec, How it's tested and Done when, each non-empty and not duplicated. An unreadable description or unknown type fails closed.
- **Story gate:** a write to a Product Backlog Item description is refused if it has a `Story:` line that does not read "As a <persona>, I want ..., so ...".

The Epic classifier also runs from the command line: `node epic-sections.mjs --classify <file>`.

## Configuration

Set these in the environment. Values are never silently trimmed; padded or control-character values are refused at startup.

| Variable | Meaning |
| --- | --- |
| `ADO_ORG` | Required. Organization name or `https://dev.azure.com/<org>`. |
| `ADO_PROJECT` | Required. Project name or GUID (up to 64 characters). |
| `AZURE_DEVOPS_EXT_PAT` | Personal access token (PAT mode). Read once at startup, held in a buffer and removed from the process environment. Not allowed in token-file mode. |
| `ADO_PROJECT_ID` | Optional GUID that pins the project; startup fails if the live project differs. Required in token-file mode. |
| `ADO_TEAM_ID` | Optional team GUID; default is the project's default team. |
| `ADO_REQUIRED_ITERATION` | Optional iteration path items are kept under. Default is resolved from the team. |
| `ADO_DEFAULT_AREA` | Optional default area path for created items. |
| `ADO_AREA_ANY_IN_PROJECT` | `1` allows writes to any area in the project, not just the team's. |
| `ADO_MCP_PORT` | Listen port, default `39251`. |
| `ADO_MCP_HOST` | Listen host. Default `127.0.0.1` (`0.0.0.0` when `ADO_MCP_CONTAINER=1`). |
| `ADO_MCP_CONTAINER` | `1` set by the Docker image so the server may bind `0.0.0.0` inside the container. |
| `ADO_MCP_ALLOW_NONLOOPBACK` | `1` overrides the refusal to listen on a non-loopback host. |

### Token-file mode (optional)

Instead of a PAT, set `ADO_AUTH_MODE=token-file`. The server then reads a JSON file (default `/run/ado-token/token.json`, override with `ADO_TOKEN_FILE`) holding an Entra access token that something else keeps fresh. It validates the file's issue time, expiry, audience and client, tenant and identity claims, and re-checks the identity against Azure DevOps. If anything fails it locks and tool calls return an error until a valid file appears; the server still starts and lists its tools. This mode requires `ADO_EXPECTED_CLIENT_ID`, `ADO_EXPECTED_TENANT_ID`, `ADO_EXPECTED_IDENTITY`, `ADO_PROJECT_NAME`, `ADO_PROJECT_ID` and `ADO_ITERATION_IS_ROOT` (`true` or `false`). `GET /auth-status` returns the auth state (never the token); `POST /auth-status` with header `X-Ado-Mcp-Probe: 1` forces a verify.

### Registry mode (optional, token-file only)

Set `ADO_MCP_REGISTRY` to a JSON file to serve several projects of one organization from one process, each at `/mcp/<key>`:

```json
{
  "version": 1,
  "organization": "contoso",
  "projects": {
    "alpha": {
      "project": "Alpha",
      "project_id": "00000000-0000-0000-0000-000000000001",
      "iteration_is_root": true,
      "area_any_in_project": false
    }
  }
}
```

Keys match `^[a-z0-9][a-z0-9-]{0,31}$`. Optional entry fields are `team_id`, `default_area` and `required_iteration`. Unknown fields, duplicate projects and a missing or malformed file are fatal at startup. A session is bound to the key it initialized with.

## Network exposure

There is no client authentication on the MCP endpoint. Security rests on where it listens:

- It binds loopback by default and refuses a non-loopback host unless `ADO_MCP_ALLOW_NONLOOPBACK=1`.
- Requests whose `Host` is not loopback with the listening port, or whose `Origin` is present and not loopback, are rejected (DNS-rebinding defense).
- In the container the server binds `0.0.0.0`, so `compose.yaml` publishes `127.0.0.1:39251:39251`. Keep that publish loopback-only; widening it exposes an unauthenticated server that acts with your credential.

## Running locally

```sh
npm ci
export ADO_ORG=contoso ADO_PROJECT=MyProject
export AZURE_DEVOPS_EXT_PAT=<your PAT>
npm start
```

It prints `ado-mcp listening on http://127.0.0.1:39251/mcp ...`. The PAT needs the scopes your use requires (work items read and write; code read for the pull request tools; build read for `ado_pr_build`).

A minimal smoke client is included: `ADO_TEST_ITEM_ID=<id of an existing item> node test-client.mjs` (it creates and changes data in the project, so point it at a sandbox). It assumes the work-item states Active, Review, QA and Closed, so it fits only a process template that has them.

## Running in Docker

```sh
export ADO_ORG=contoso ADO_PROJECT=MyProject AZURE_DEVOPS_EXT_PAT=<your PAT>
docker compose up --build
```

The image is `node:22-alpine` pinned by digest, installs production dependencies from the lockfile with `npm ci`, and runs as the non-root `node` user. To pass the PAT on stdin instead of the environment, override the entrypoint with the one-line `sh -c` string documented in `entrypoint-stdin.sh`; end-of-file or an empty line exits 1.

## Registering with Claude Code

```sh
claude mcp add --transport http ado http://127.0.0.1:39251/mcp
```

In registry mode use `http://127.0.0.1:39251/mcp/<key>`. The initialize response carries the enforced scope, and `ado_identity` shows it.

## Testing

```sh
npm test
```

Runs the Node built-in test runner over `test/*.test.mjs`. Tests use fake fetch implementations and a fetch stub; they make no network calls. They also check that the Dockerfile copies every module reachable from `server.mjs`, and that every script, module or yaml file named in a tracked file exists (`test/referenced-files.test.mjs`).

### What is tested

- Unit tests with stubs: the server and its guards against fake `fetch` responses; the token hook and comment guard against synthetic hook input; the PowerShell scripts through their dry-run, parse and plan paths and fixtures.
- Not tested here: no `-Apply` run of any `host/admin` step has been made from this repository, and nothing has been run against a live Azure DevOps organization, Key Vault or Entra tenant. The negative matrix (step 4) is the live test; run it in your own sandbox before you trust the setup.

## Design notes

- **Total classification, fail closed.** Every guard maps every input to an explicit allow or a visible error; unknown, malformed or unreadable input is refused, never allowed by default.
- **Scope is checked twice.** Queries are constrained to the project, and each fetched item is checked again before it is returned or changed.
- **Credentials stay out of reach.** The PAT is held in a buffer and removed from the environment; auth-status output and error text never include token content.
- **No self-approval.** The pull request tools can read, check CI, publish a draft the service principal created, and link a work item. They cannot vote, approve or complete.
- **Nothing is inferred.** Hours, estimates and `completedWork` are written only when supplied.
- **Idempotent and guarded writes.** Work item links use a revision test; tag edits are verified against the response rather than assumed.

## License

MIT. See LICENSE.