{
  "markdown": "# Unleash MCP Server\n\nA purpose-driven [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for managing [Unleash](https://www.getunleash.io/) feature flags. This server enables LLM-powered coding assistants to create and manage feature flags following Unleash best practices.\n\nTo share feedback, join our [community Slack](https://www.getunleash.io/unleash-community) or open an [issue on GitHub](https://github.com/Unleash/unleash-mcp/issues).\n\n## Overview\n\nThis MCP server provides tools that integrate with the [Unleash Admin API](https://docs.getunleash.io/understanding-unleash/unleash-overview#admin-api), allowing AI coding assistants to:\n\n- **Create feature flags** with proper validation and typing.\n- **Detect existing flags** to prevent duplicates or encourage reuse.\n- **Evaluate changes** to decide when a feature flag is needed.\n- **Stream progress** for visibility during operations.\n- **Handle errors** gracefully with helpful hints.\n- **Follow best practices** from the [Unleash documentation](https://docs.getunleash.io/topics/feature-flags/best-practices-using-feature-flags-at-scale).\n\n### Available tools\n\nThe MCP server exposes the following tools:\n\n- `create_flag`: Creates a feature flag in Unleash.\n- `evaluate_change`: Scores risk and recommends feature flag usage.\n- `detect_flag`: Discovers existing feature flags to avoid duplicates.\n- `wrap_change`: Provides guidance on how to wrap a change in a feature flag.\n- `set_flag_rollout`: Configures rollout strategies for a feature flag (does not enable the flag).\n- `get_flag_state`: Surfaces a feature flag's metadata and its activation strategies.\n- `list_flags`: Lists all feature flags in a project, with optional pagination and sort order.\n- `list_projects`: Lists Unleash projects available to the configured token, with optional pagination.\n- `toggle_flag_environment`: Enables or disables a feature flag in an environment.\n- `remove_flag_strategy`: Deletes a feature flag's strategy from an environment.\n- `cleanup_flag`: Generates instructions for safely removing flagged code paths.\n\n### Core workflow\n\nThe core workflow for an AI assistant is designed to be:\n1. `evaluate_change`: First, assess a code change to see if a flag is needed.\n2. `detect_flag`: This is often called automatically by `evaluate_change` to prevent creating duplicate flags.\n3. `create_flag`: If a new flag is required, this tool creates it in Unleash.\n4. `wrap_change`: Finally, this tool provides the language-specific code to implement the new flag.\n\nSee more information on the core workflow tools in the [Tool reference](#tool-reference) section.\n\n## Prerequisites\n\nBefore you can run the server, you need the following:\n- Node.js 22 or higher\n- pnpm package manager or npm\n- An Unleash instance (hosted or self-hosted)\n- A [personal access token](https://docs.getunleash.io/reference/api-tokens-and-client-keys#personal-access-tokens) with permissions to create feature flags\n\n## Get started\n\nThis section covers the different ways to install and run the Unleash MCP server. You can either follow a setup for [agents](#agent-setup) (such as Claude Code and Codex), run the MCP as a [standalone process](#quickstart-with-npx) using npx, or use a [local development](#local-development-setup) setup.\n\n### Agent setup\n\nYou can add the MCP server directly to Claude Code or Codex. Agent configurations are path-specific. You must run the following command from the root directory of the project where you want to use the MCP.\n\nFor Claude Code:\n\n```\nclaude mcp add unleash \\\n    --env UNLEASH_BASE_URL={{your-instance-url}} \\\n    --env UNLEASH_PAT={{your-personal-access-token}} \\\n    -- npx -y @unleash/mcp@latest --log-level error\n```\n\nFor Codex:\n```\ncodex mcp add unleash \\\n    --env UNLEASH_BASE_URL={{your-instance-url}} \\\n    --env UNLEASH_PAT={{your-personal-access-token}} \\\n    -- npx -y @unleash/mcp@latest --log-level error\n```\n\n### Remote agent setup (experimental)\n\nInstead of running the MCP server locally, you can connect directly to your Unleash instance's built-in remote MCP server over HTTP. This uses the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) — no local process needed.\n\n> **Note:** Remote MCP is an experimental feature that must be enabled on your Unleash instance. Contact the Unleash team to get it enabled.\n\n#### OAuth\n\nThe OAuth flow opens your browser, lets you log in to Unleash, and automatically provisions a short-lived PAT. No manual token management required.\n\nFor Claude Code:\n\n```bash\nclaude mcp add unleash https://{{your-instance-url}}/api/admin/mcp --transport http\n```\n\nFor Codex:\n\n```bash\ncodex mcp add unleash https://{{your-instance-url}}/api/admin/mcp --transport http\n```\n\nOn first use, the client will automatically open your browser for login. After authenticating with Unleash, a PAT is created and used for all subsequent requests.\n\nThe PAT expires after 24 hours by default.\n\n#### Personal Access Token (PAT)\n\nUse this method when you already have a PAT or need headless/non-interactive access (CI pipelines, shared developer environments, clients that don't support OAuth).\n\nTo create a PAT: log in to your Unleash instance, go to **Profile** > **Personal Access Tokens**, and create a new token.\n\nFor Claude Code:\n\n```bash\nclaude mcp add unleash https://{{your-instance-url}}/api/admin/mcp \\\n  --transport http \\\n  --header \"Authorization: Bearer {{your-personal-access-token}}\"\n```\n\nFor Codex:\n\n```bash\ncodex mcp add unleash https://{{your-instance-url}}/api/admin/mcp \\\n  --transport http \\\n  --header \"Authorization: Bearer {{your-personal-access-token}}\"\n```\n\nThe `--header` flag sends the PAT directly, bypassing the OAuth flow entirely.\n\n### Quickstart with npx\n\nYou can run the MCP server as a standalone process without cloning the repository using `npx`. Provide configuration through environment variables or a local `.env` file in the directory where you run the command:\n\n```bash\nUNLEASH_BASE_URL={{your-instance-url}} \\\nUNLEASH_PAT={{your-personal-access-token}} \\\nUNLEASH_DEFAULT_PROJECT={{default_project_id}} \\\nnpx @unleash/mcp@latest --log-level debug\n```\n\nThe CLI supports the same flags as the local build (for example, `--dry-run`, `--log-level`).\n\n### Local development setup\n\nFollow these steps to set up the project for local development.\n\n1. **Install dependencies**\n\nClone the repository and install dependencies using pnpm. Corepack keeps everyone on the same pnpm version:\n\n```bash\ngit clone https://github.com/Unleash/unleash-mcp.git\ncd unleash-mcp\n\n# Enable Corepack once per machine, then prepare the pnpm this repo expects\ncorepack enable\ncorepack prepare pnpm@11.0.8 --activate\n\npnpm install\n```\n\n2) **Run in dev mode directly from Claude or Codex**\n\nAvoid `npm run` output and `tsx watch` banners because any extra stdout breaks the MCP handshake. Two quiet options:\n\n**A) Use compiled JS (most reliable)**\n```\nnpm run build\n# or keep it hot in another terminal: npm run build:watch\n\nclaude mcp add unleash-dev \\\n  --env UNLEASH_BASE_URL={{your-instance-url}} \\\n  --env UNLEASH_PAT={{your-personal-access-token}} \\\n  --env LOG_LEVEL=debug \\\n  --env APP_LOG_FILE=\"$(pwd)/app.log\" \\\n  --env MCP_STDIO_LOG_FILE=\"$(pwd)/mcp-stdio.log\" \\\n  -- node \"$(pwd)/dist/index.js\"\n\ncodex mcp add unleash-dev \\\n  --env UNLEASH_BASE_URL={{your-instance-url}} \\\n  --env UNLEASH_PAT={{your-personal-access-token}} \\\n  --env LOG_LEVEL=debug \\\n  --env APP_LOG_FILE=\"$(pwd)/app.log\" \\\n  --env MCP_STDIO_LOG_FILE=\"$(pwd)/mcp-stdio.log\" \\\n  -- node \"$(pwd)/dist/index.js\"\n```\n\n**B) Use TypeScript directly (no build)**\n```\nclaude mcp add unleash-dev \\\n  --env UNLEASH_BASE_URL={{your-instance-url}} \\\n  --env UNLEASH_PAT={{your-personal-access-token}} \\\n  --env LOG_LEVEL=debug \\\n  --env APP_LOG_FILE=\"$(pwd)/app.log\" \\\n  --env MCP_STDIO_LOG_FILE=\"$(pwd)/mcp-stdio.log\" \\\n  -- node --no-warnings --import tsx \"$(pwd)/src/index.ts\"\n\ncodex mcp add unleash-dev \\\n  --env UNLEASH_BASE_URL={{your-instance-url}} \\\n  --env UNLEASH_PAT={{your-personal-access-token}} \\\n  --env LOG_LEVEL=debug \\\n  --env APP_LOG_FILE=\"$(pwd)/app.log\" \\\n  --env MCP_STDIO_LOG_FILE=\"$(pwd)/mcp-stdio.log\" \\\n  -- node --no-warnings --import tsx \"$(pwd)/src/index.ts\"\n```\n\nNotes:\n- `node --import tsx` is quiet (no npm lifecycle output) and runs TS directly; use this when you want to avoid building.\n- `node dist/index.js` is the safest choice; pair it with `npm run build:watch` to rebuild on changes while the agent command stays stable.\n- Logs stay in the repo root (`app.log`, `mcp-stdio.log`), both gitignored.\n\n### Logging control\n\n- `LOG_LEVEL` (preferred): controls application logging verbosity (`debug`, `info`, `warn`, `error`). Defaults to `error` when unset.\n- `--log-level` CLI flag: optional override for `LOG_LEVEL` when you want a one-off change.\n- `APP_LOG_FILE` (optional): if set, application logs are written to this file (not stdout). If unset, logs go to stderr.\n- `MCP_STDIO_LOG_FILE` (optional): if set, MCP stdin/stdout/stderr are tee’d into this single file with channel prefixes. Protocol messages still flow over stdout normally.\n\n### Client attribution\n\nWhen an MCP client sends `clientInfo` during initialization (Claude Code, Cursor, Copilot, Windsurf, Codex, Kiro, and other conforming clients), the server enriches the `User-Agent` header on outbound Unleash Admin API calls:\n\n```\nUser-Agent: unleash-mcp/<version> (MCP Server; client=claude-code/1.2.3)\n```\n\nThis makes Unleash event logs answer \"which AI tool created or toggled this flag\" without any server-side changes. Attribution values are sanitized so they cannot break the User-Agent header.\n\nSet `UNLEASH_MCP_CLIENT_ATTRIBUTION=off` to disable enrichment and revert to `unleash-mcp/<version> (MCP Server)`. Default: enabled.\n\n## Tool reference\n\nThis section describes each of the core tools in detail, including its purpose, parameters, and output.\n\n### Create flag\n\nThe `create_flag` tool creates a new feature flag in Unleash with comprehensive validation and progress tracking. \n\n#### When to use\n\nUse this tool when you have already determined that a feature flag is required (for example, after running `evaluate_change`) and you are ready to create it with the correct type and metadata.\n\n#### Parameters\n\nThe tool accepts the following parameters:\n- `name` (required): Unique feature flag name within the project.\n- `type` (required): Feature flag type indicating lifecycle and intent.\n  - `release`: Gradual feature rollouts to users.\n  - `experiment`: A/B tests and experiments.\n  - `operational`: System behavior and operational toggles.\n  - `kill-switch`: Emergency shutdowns or circuit breakers.\n  - `permission`: Control feature access based on user roles or entitlements.\n- `description` (required): Clear explanation of what the flag controls and why it exists.\n- `projectId` (optional): Target project (defaults to `UNLEASH_DEFAULT_PROJECT`).\n- `impressionData` (optional): Enable analytics tracking (defaults to false).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse create_flag with:\n- name: \"new-checkout-flow\"\n- type: \"release\"\n- description: \"Gradual rollout of the redesigned checkout experience\"\n- projectId: \"ecommerce\"\n```\n\n**Tool payload**\n```json\n{\n  \"name\": \"new-checkout-flow\",\n  \"type\": \"release\",\n  \"description\": \"Gradual rollout of the redesigned checkout experience with improved conversion tracking\",\n  \"projectId\": \"ecommerce\",\n  \"impressionData\": true\n}\n```\n\n**Tool output**\n\nOn success, the tool returns a JSON object containing the new feature flag's URL in the Unleash Admin UI, an MCP resource link for programmatic access, creation timestamp, and configuration details.\n\n### Evaluate change\n\nThe `evaluate_change` tool evaluates whether a code change should be behind a feature flag. It examines the structure, context, and potential risk of the change and returns a recommendation with an explanation and next steps.\n\n#### When to use\n\nUse `evaluate_change` at the beginning of a feature or modification when you want to understand whether the work requires a feature flag. This tool is also helpful when you are unsure which flag type to use or want guidance on rollout planning.\n\n#### How it works\nThe tool returns detailed, markdown-formatted guidance for the LLM assistant based on [Unleash best practices](https://docs.getunleash.io/topics/feature-flags/best-practices-using-feature-flags-at-scale).\n\nThe guidance includes:\n- **Parent flag detection**: Checks if code is already protected by existing flags.\n- **Risk assessment**: Analyzes code patterns to identify risky operations.\n- **Code type evaluation**: Classifies the change (for example, test, config, feature, or bug fix).\n- **Recommendation**: Suggests whether to create a flag, use an existing flag, or skip the flag.\n- **Next actions**: Provides specific instructions on what to do next.\n\nWhen `evaluate_change` determines a flag is needed, it provides explicit instructions to:\n\n1. Call `create_flag` tool to create the feature flag.\n2. Call `wrap_change` tool to get language-specific code wrapping guidance.\n3. Implement the wrapped code following the detected patterns.\n\n**The evaluation process**\n\nThe tool follows a clear evaluation process:\n\n```\nStep 1: Gather code changes (git diff, read files)\n        ↓\nStep 2: Check for parent flags (avoiding nesting)\n        ↓\nStep 3: Assess code type (test? config? feature?)\n        ↓\nStep 4: Evaluate risk (auth? payments? API changes?)\n        ↓\nStep 5: Calculate risk score\n        ↓\nStep 6: Make recommendation\n        ↓\nStep 7: Take action (create flag or proceed without)\n```\n\n**Risk assessment**\n\nThe tool uses language-agnostic patterns to score risk:\n- **Critical risk** (Score +5): For example, auth, payments, security, and database operations.\n- **High risk** (Score +3): For example, API changes, external services, or new classes.\n- **Medium risk** (Score +2): For example, async operations or state management.\n- **Low risk** (Score +1): For example, bug fixes, refactors, or small changes.\n\nScores accumulate across matched categories. The total maps to a risk level:\n- **Critical**: Score ≥ 5\n- **High**: Score ≥ 3\n- **Medium**: Score ≥ 2\n- **Low**: Score < 2\n\nThe output includes a `confidence` score (0-1) representing the LLM's self-assessed certainty, which increases with more context provided.\n\nAn **excluded** category covers files that do not need feature flags regardless of content: test files (`*.test.ts`, `*_test.go`, etc.), configuration files (`*.config.js`, `.env`, `*.yaml`), and documentation files (`*.md`, `docs/**`). Changes limited to excluded files will not trigger a flag recommendation.\n\nThe full pattern definitions, including per-category keywords, file globs, code patterns, and reasoning, are in [`src/evaluation/riskPatterns.ts`](src/evaluation/riskPatterns.ts).\n\n**Parent flag detection**\n\nThe tool looks for common patterns across languages, such as:\n- **Conditionals**: `if (isEnabled('flag'))`, `if client.is_enabled('flag'):`\n- **Assignments**: `const enabled = useFlag('flag')`\n- **Hooks**: `const enabled = useFlag('flag')` → `{enabled && <Component />}`\n- **Guards**: `if (!isEnabled('flag')) return;`\n- **Wrappers**: `withFeatureFlag('flag', () => {...})`\n\n#### Parameters\n\nAll parameters are optional, but more context leads to better recommendations:\n- `repository` (string): Repository name or path.\n- `branch` (string): Current branch name.\n- `files` (array): List of files being changed.\n- `description` (string): Description of the change.\n- `riskLevel` (enum): `low`, `medium`, `high`, or `critical`, as assessed by the user.\n- `codeContext` (string): Surrounding code for parent flag detection.\n\n#### Usage example\n\n**Agent prompt**\n\nSimple usage where you let the agent gather context:\n```\nUse evaluate_change to help me determine if I need a feature flag\n```\n\nExplicit instructions:\n```\nUse evaluate_change with:\n- description: \"Add Stripe payment processing\"\n- riskLevel: \"high\"\n```\n\n**Tool payload**\n\n```json\n{\n  \"repository\": \"my-app\",\n  \"branch\": \"feature/stripe-integration\",\n  \"files\": [\"src/payments/stripe.ts\"],\n  \"description\": \"Add Stripe payment processing\",\n  \"riskLevel\": \"high\",\n  \"codeContext\": \"surrounding code for parent flag detection\"\n}\n```\n\n**Tool output**\n\nReturns a JSON object with the evaluation result, including a `needsFlag` boolean, a `recommendation` (e.g., \"create_new\"), a suggested flag name, risk level, and a detailed `explanation`.\n\n```json\n{\n  \"needsFlag\": true,\n  \"reason\": \"new_feature\",\n  \"recommendation\": \"create_new\",\n  \"suggestedFlag\": \"stripe-payment-integration\",\n  \"riskLevel\": \"critical\",\n  \"riskScore\": 5,\n  \"explanation\": \"This change integrates Stripe payments, which is critical risk...\",\n  \"confidence\": 0.9\n}\n```\n\n### Detect flag\n\nThe `detect_flag` tool finds existing feature flags in the codebase so you can reuse them instead of creating duplicates. This tool is automatically integrated into the `evaluate_change` workflow but can also be used manually.\n\n#### When to use\n\nUse this tool before creating a new feature flag or during code evaluation to check for existing flags that might already cover your use case. This helps prevent flag duplication.\n\n#### How it works\n\nThe tool returns comprehensive search instructions and uses multiple detection strategies:\n- **File-based detection**: Search in files you're modifying for existing flags.\n- **Git history analysis**: Look for recently added flags in commit history.\n- **Semantic name matching**: Match descriptions to existing flag names.\n- **Code context analysis**: Inspect code around the change.\n\nThe tool then follows a scoring process:\n\n```\nStep 1: Execute file-based search (grep for flag patterns in target files)\n        ↓\nStep 2: Search git history for recent flag additions\n        ↓\nStep 3: Perform semantic matching (description → flag names)\n        ↓\nStep 4: Analyze code context (if provided)\n        ↓\nStep 5: Combine scores from all methods\n        ↓\nStep 6: Return best candidate with confidence score\n```\n\n**Confidence levels**\n\nThe tool returns candidates with confidence scores:\n\n- High `≥0.7`: Strong match; reuse is recommended.\n- Medium `0.4-0.7`: Possible match; review manually.\n- Low `<0.4`: Weak match; likely create a new flag.\n\n#### Parameters\n\n- `description` (required): Description of the change or feature. For example, `\"payment processing with Stripe\"`, `\"new checkout flow\"`.\n- `files` (optional): Files being modified. For example, `[\"src/payments/stripe.ts\", \"src/checkout/flow.ts\"]`.\n- `codeContext` (optional): Nearby code to scan for flags.\n\n#### Usage example\n\n**Agent prompt**\n\nCheck for existing flags before creating a flag:\n```\nUse detect_flag with description \"payment processing with Stripe\"\n```\n\nIntegrated automatically in evaluation:\n```\nUse evaluate_change - automatically searches for existing flags\n```\n\n**Tool payload**\n\n```json\n{\n  \"description\": \"payment processing with Stripe\",\n  \"files\": [\"src/payments/stripe.ts\"]\n}\n```\n\n**Tool output**\n\nReturns a JSON object indicating if a flag was found. If `flagFound` is true, it includes a `candidate` object with the flag's name, location, confidence score, and the reason for the match.\n\nMatch found:\n```json\n{\n  \"flagFound\": true,\n  \"candidate\": {\n    \"name\": \"stripe-payment-integration\",\n    \"location\": \"src/payments/stripe.ts:42\",\n    \"context\": \"if (client.isEnabled('stripe-payment-integration')) {\",\n    \"confidence\": 0.85,\n    \"reasoning\": \"Found in same file you're modifying, added 2 days ago\",\n    \"detectionMethod\": \"file-based\"\n  }\n}\n```\n\nNo match found:\n\n```json\n{\n  \"flagFound\": false,\n  \"candidate\": null\n}\n```\n\n### Wrap change\n\nThe tool `wrap_change` generates language-specific code snippets and guidance for wrapping code with feature flags. It helps LLMs and developers follow existing patterns in the codebase and use flags correctly.\n\n#### When to use\nUse this tool after you have created a feature flag (with `create_flag`) and need to implement it in your code. It's especially useful when you want to ensure you are following existing codebase patterns or need framework-specific examples (e.g., React, Django).\n\n#### How it works\n\nThis tool is the final step in the `evaluate_change` → `create_flag` → `wrap_change` workflow.\n\nThe tool provides the following guidance in its response:\n1. **Search instructions**: Step-by-step guide for finding existing flag patterns in your codebase using grep.\n2. **Pattern detection**: Identifies common patterns (for example, imports, client variable names, method names, or wrapping styles).\n3. **Default templates**: Fallback code snippets if no patterns are found.\n4. **Framework-specific examples**: Specialized patterns for React, Express, Django, and others.\n5. **Multiple patterns**: If-blocks, guard clauses, hooks, decorators, middleware, and more.\n\n**Supported languages and frameworks:**\n\n- **TypeScript/JavaScript**: Node.js, React Hooks, Express middleware.\n- **Python**: FastAPI, Django, Flask decorators.\n- **Go**: Standard if-blocks, HTTP middleware.\n- **Ruby**: Rails controllers.\n- **PHP**: Laravel controllers.\n- **C#**: .NET/ASP.NET controllers.\n- **Java**: Spring Boot.\n- **Rust**: Actix/Rocket handlers.\n\n#### Parameters\n\n- `flagName` (required): Feature flag name to wrap the code with. For example: `\"new-checkout-flow\"`, or `\"stripe-integration\"`.\n- `language` (optional): Programming language (auto-detected from `fileName` if not provided). Supported: `typescript`, `javascript`, `python`, `go`, `ruby`, `php`, `csharp`, `java`, `rust`\n- `fileName` (optional): File name being modified (helps detect language), For example: `\"checkout.ts\"`, `\"payment.py\"`, or `\"handler.go\"`.\n- `codeContext` (optional): Surrounding code to help detect existing patterns.\n- `frameworkHint` (optional): Framework for specialized templates. For example, `\"React\"`, `\"Express\"`, `\"Django\"`, `\"Rails\"`, or `\"Spring Boot\"`.\n\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse wrap_change with:\n- flagName: \"new-checkout-flow\"\n- fileName: \"src/components/checkout.ts\"\n- frameworkHint: \"React\"\n```\n\n**Tool payload**\n\n```json\n{\n  \"flagName\": \"new-checkout-flow\",\n  \"fileName\": \"checkout.ts\",\n  \"frameworkHint\": \"React\"\n}\n```\n\n**Tool output**\n\nReturns a comprehensive, markdown-formatted string that guides the user on how to wrap their code. This includes a quickstart, search instructions, wrapping instructions with placeholders, all available templates for the language, and links to SDK documentation.\n\n```markdown\n# Feature Flag Wrapping Guide: \"new-checkout-flow\"\n\n**Language:** TypeScript\n**Framework:** React\n\n## Quick Start\n[Recommended pattern with import and usage]\n\n## How to Search for Existing Flag Patterns\n[Step-by-step Grep instructions]\n\n## How to Wrap Code with Feature Flag\n[Wrapping instructions with examples]\n\n## All Available Templates\n[If-block, guard clause, hooks, ternary, etc.]\n```\n\n### Set flag rollout\n\nThe `set_flag_rollout` tool configures a `flexibleRollout` strategy on a feature flag environment. It sets the rollout percentage, stickiness, and optional strategy-level variants. This does not enable the flag; use `toggle_flag_environment` to turn it on.\n\n#### When to use\n\nUse this tool after creating a flag with `create_flag` to configure how traffic is distributed before enabling it. Also use it to update an existing rollout percentage or add variants.\n\n#### Parameters\n\n- `featureName` (required): Feature flag name.\n- `environment` (required): Target environment (for example, `\"production\"`, `\"development\"`).\n- `rolloutPercentage` (required): Percentage of traffic to receive the feature (0-100).\n- `projectId` (optional): Project ID (defaults to `UNLEASH_DEFAULT_PROJECT`).\n- `groupId` (optional): Stickiness bucketing key (defaults to the feature name).\n- `stickiness` (optional): Stickiness field (defaults to `\"default\"`).\n- `title` (optional): Descriptive title for the strategy.\n- `disabled` (optional): Create the strategy in a disabled state (defaults to false).\n- `variants` (optional): List of strategy-level variants, each with `name`, `weight` (0-1000), optional `weightType` (`\"variable\"` or `\"fix\"`), `stickiness`, and `payload` (`{type, value}`).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse set_flag_rollout with:\n- featureName: \"new-checkout-flow\"\n- environment: \"production\"\n- rolloutPercentage: 25\n```\n\n**Tool payload**\n\n```json\n{\n  \"featureName\": \"new-checkout-flow\",\n  \"environment\": \"production\",\n  \"rolloutPercentage\": 25,\n  \"projectId\": \"ecommerce\",\n  \"stickiness\": \"userId\"\n}\n```\n\n**Tool output**\n\nReturns a confirmation with the configured percentage, a link to the flag in the Unleash Admin UI, the Admin API strategies URL, and an MCP resource link for the flag.\n\n### Get flag state\n\nThe `get_flag_state` tool fetches a feature flag's current metadata and environment strategies from the Unleash Admin API. It returns the flag's type, enabled/archived status, impression data setting, and a per-environment summary of active strategies and variants.\n\n#### When to use\n\nUse this tool to inspect a flag before modifying it, to check how many strategies are active across environments, or to find strategy IDs before calling `remove_flag_strategy`.\n\n#### Parameters\n\n- `featureName` (required): Feature flag name.\n- `projectId` (optional): Project ID (defaults to `UNLEASH_DEFAULT_PROJECT`).\n- `environment` (optional): Filter results to a single environment (case-insensitive).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse get_flag_state with:\n- featureName: \"new-checkout-flow\"\n- environment: \"production\"\n```\n\n**Tool payload**\n\n```json\n{\n  \"featureName\": \"new-checkout-flow\",\n  \"projectId\": \"ecommerce\",\n  \"environment\": \"production\"\n}\n```\n\n**Tool output**\n\nReturns a text summary of the flag (type, enabled/archived/impression-data, project, environment summaries with strategy counts) along with UI and API links. The structured output includes the full feature object with all environments and strategy details.\n\n### List flags\n\nThe `list_flags` tool enumerates the feature flags in a project and returns a structured inventory with pagination and sort order. Active and archived flags are returned separately: call it once with `archived: false` (the default) and once with `archived: true` to assemble a full inventory for audit workflows.\n\n#### When to use\n\nUse this tool when an agent needs to discover which flags already exist, for example to audit a project, find candidates for cleanup, or build context before creating or wrapping a flag. It is the agent-invokable equivalent of the `unleash://projects/{projectId}/feature-flags` resource (see [MCP resources](#mcp-resources)).\n\n#### Parameters\n\n- `projectId` (optional): Project to list flags from (defaults to `UNLEASH_DEFAULT_PROJECT`; auto-resolved when a single project exists).\n- `archived` (optional): `true` to list archived flags instead of active ones. Defaults to `false`. Active and archived flags cannot be returned in the same response.\n- `limit` (optional): Maximum flags per page (default: server page size, typically 50).\n- `order` (optional): Sort order by flag name, `asc` or `desc` (default: `asc`).\n- `offset` (optional): Number of flags to skip for pagination (default: 0).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse list_flags with:\n- projectId: \"ecommerce\"\n- archived: false\n```\n\n**Tool payload**\n\n```json\n{\n  \"projectId\": \"ecommerce\",\n  \"archived\": false,\n  \"limit\": 50,\n  \"order\": \"asc\"\n}\n```\n\n**Tool output**\n\nReturns a text summary plus structured content with `projectId`, `archived`, `order`, `limit`, `offset`, `nextOffset`, `totalFlags`, and the `flags` array (each with name, type, project, archived status, and links). Use `nextOffset` to page through large projects.\n\n### List projects\n\nThe `list_projects` tool enumerates the Unleash projects available to the configured token, with pagination and sort order.\n\n#### When to use\n\nUse this tool when the target project is unknown, or when an agent needs to pick a project before listing or creating flags. It is the agent-invokable equivalent of the `unleash://projects` resource (see [MCP resources](#mcp-resources)).\n\n#### Parameters\n\n- `limit` (optional): Maximum projects per page (default: server page size, typically 20).\n- `order` (optional): Sort order by project creation time, `asc` or `desc` (default: `desc`, newest first).\n- `offset` (optional): Number of projects to skip for pagination (default: 0).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse list_projects to see which projects are available.\n```\n\n**Tool payload**\n\n```json\n{\n  \"limit\": 20,\n  \"order\": \"desc\"\n}\n```\n\n**Tool output**\n\nReturns a text summary plus structured content with `order`, `limit`, `offset`, `nextOffset`, `totalProjects`, and the `projects` array (each with id, name, description, mode, creation time, and URL).\n\n### Toggle flag environment\n\nThe `toggle_flag_environment` tool enables or disables a feature flag in a specific environment. For gradual rollouts, configure a strategy with `set_flag_rollout` before enabling.\n\n#### When to use\n\nUse this tool to turn a flag on after configuring a rollout strategy, or to disable a flag during an incident or after completing a rollout.\n\n#### Parameters\n\n- `featureName` (required): Feature flag name.\n- `environment` (required): Environment to toggle (for example, `\"production\"`).\n- `enabled` (required): `true` to enable, `false` to disable.\n- `projectId` (optional): Project ID (defaults to `UNLEASH_DEFAULT_PROJECT`).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse toggle_flag_environment with:\n- featureName: \"new-checkout-flow\"\n- environment: \"production\"\n- enabled: true\n```\n\n**Tool payload**\n\n```json\n{\n  \"featureName\": \"new-checkout-flow\",\n  \"environment\": \"production\",\n  \"enabled\": true,\n  \"projectId\": \"ecommerce\"\n}\n```\n\n**Tool output**\n\nReturns a confirmation of the new state, a summary of the environment (enabled/disabled, strategy count), and links to the flag in the Unleash Admin UI and Admin API.\n\n### Remove flag strategy\n\nThe `remove_flag_strategy` tool deletes a strategy configuration from a feature flag environment. Use `get_flag_state` first to discover the strategy ID.\n\n#### When to use\n\nUse this tool to clean up stale strategies, or to replace an existing strategy by removing the old one and configuring a new one with `set_flag_rollout`.\n\n#### Parameters\n\n- `featureName` (required): Feature flag name.\n- `environment` (required): Environment from which to remove the strategy.\n- `strategyId` (required): ID of the strategy to remove (find this via `get_flag_state`).\n- `projectId` (optional): Project ID (defaults to `UNLEASH_DEFAULT_PROJECT`).\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse get_flag_state to find strategy IDs for \"new-checkout-flow\" in production,\nthen use remove_flag_strategy to delete the old strategy.\n```\n\n**Tool payload**\n\n```json\n{\n  \"featureName\": \"new-checkout-flow\",\n  \"environment\": \"production\",\n  \"strategyId\": \"a1b2c3d4-e5f6-7890-abcd-ef1234567890\",\n  \"projectId\": \"ecommerce\"\n}\n```\n\n**Tool output**\n\nReturns a confirmation of removal, a count of remaining strategies in the environment, and links to the flag in the Unleash Admin UI and Admin API.\n\n### Cleanup flag\n\nThe `cleanup_flag` tool generates step-by-step instructions for safely removing feature flag code from the codebase while preserving the desired code path.\n\n#### When to use\n\nUse this tool when a feature flag has completed its lifecycle:\n- After a rollout reaches 100% and the flag is no longer needed.\n- When deprecating an experimental feature (preserve the disabled path).\n- When removing a kill switch that is no longer necessary.\n- During technical debt cleanup of old flags.\n\n#### How it works\n\nThe tool returns comprehensive cleanup instructions that guide the LLM through:\n1. Finding all occurrences of the flag using grep patterns.\n2. Identifying usage patterns (if-else blocks, ternary expressions, guard clauses, hooks, decorators, middleware).\n3. Removing flag checks while preserving the correct code path.\n4. Cleaning up unused imports with language-specific guidance.\n5. Verifying changes with post-cleanup search and test steps.\n\nIf `preservePath` is not provided, the tool returns instructions to ask the user which path to keep before proceeding.\n\n#### Parameters\n\n- `flagName` (required): Name of the feature flag to remove (for example, `\"new-checkout-flow\"`).\n- `preservePath` (optional): `\"enabled\"` to keep the flag-on code path (typical for completed rollouts), or `\"disabled\"` to keep the flag-off path (for removed experiments). If omitted, the tool prompts you to ask the user.\n- `files` (optional): Specific files to clean up. If omitted, searches the entire codebase.\n- `language` (optional): Programming language for specialized import cleanup guidance (for example, `\"typescript\"`, `\"python\"`). Auto-detected from `files` if not provided.\n\n#### Usage example\n\n**Agent prompt**\n\n```\nUse cleanup_flag with:\n- flagName: \"new-checkout-flow\"\n- preservePath: \"enabled\"\n```\n\n**Tool payload**\n\n```json\n{\n  \"flagName\": \"new-checkout-flow\",\n  \"preservePath\": \"enabled\",\n  \"files\": [\"src/components/checkout.tsx\", \"src/api/checkout.ts\"],\n  \"language\": \"typescript\"\n}\n```\n\n**Tool output**\n\nReturns a markdown guide covering the cleanup scope and preserved path, grep commands to find all occurrences, per-pattern removal instructions, language-specific import cleanup, and post-cleanup verification steps (re-search, run tests, manual review).\n\n## MCP resources\n\nThe server registers MCP [resources](https://modelcontextprotocol.io/docs/concepts/resources) for reading project and feature flag data. All resources return JSON and are cached for 60 seconds.\n\n| URI template | Description |\n|---|---|\n| `unleash://projects{?limit,order,offset}` | List projects. Default page size: 20, sorted by creation time (newest first). |\n| `unleash://projects/{projectId}/feature-flags{?limit,order,offset}` | List flags in a project. Default page size: 50, sorted alphabetically. |\n| `unleash://projects/{projectId}/feature-flags/{flagName}` | Single feature flag metadata. |\n\nThe first two templates accept optional query parameters: `limit` (page size), `order` (`asc` or `desc`), and `offset` (pagination start). Responses include `fetchedAt`, `cached`, `totalProjects` or `totalFlags`, and `nextOffset` fields.\n\n> **Resources vs. tools:** MCP resources are application-controlled, so many clients only surface them through user-driven UI (for example `#`-mentions) and do not let the agent call `resources/read` on its own. When an agent needs to enumerate projects or flags programmatically, use the `list_projects` and `list_flags` tools, which return the same data through the tool interface. The `detect_flag` inventory analysis routes through the same path.\n\n**Example resource read**\n\n```\nRead unleash://projects/ecommerce/feature-flags?limit=10&order=asc\n```\n\nReturns the first 10 feature flags in the `ecommerce` project, sorted alphabetically, with pagination metadata.\n\n## Architecture\n\nThe server follows a focused, purpose-driven design.\n\n### Structure\n\n```\nsrc/\n├── index.ts                     # Stdio CLI entry point\n├── server.ts                    # Transport-agnostic server factory\n├── remote.ts                    # HTTP request handler for embedded mode\n├── config.ts                    # Configuration loading and validation\n├── context.ts                   # Shared runtime context\n├── version.ts                   # Version constant\n├── unleash/\n│   └── client.ts                # Unleash Admin API client\n├── tools/\n│   ├── types.ts                 # Shared ToolDefinition type\n│   ├── createFlag.ts            # create_flag tool\n│   ├── evaluateChange.ts        # evaluate_change tool\n│   ├── detectFlag.ts            # detect_flag tool\n│   ├── wrapChange.ts            # wrap_change tool\n│   ├── cleanupFlag.ts           # cleanup_flag tool\n│   ├── setFlagRollout.ts        # set_flag_rollout tool\n│   ├── getFlagState.ts          # get_flag_state tool\n│   ├── toggleFlagEnvironment.ts # toggle_flag_environment tool\n│   └── removeFlagStrategy.ts    # remove_flag_strategy tool\n├── resources/\n│   └── unleashResources.ts      # MCP resource handlers (projects, flags)\n├── prompts/\n│   └── promptBuilder.ts         # Markdown formatting utilities\n├── evaluation/\n│   ├── riskPatterns.ts          # Risk assessment patterns\n│   └── flagDetectionPatterns.ts # Parent flag detection patterns\n├── detection/\n│   ├── flagDiscovery.ts         # Flag discovery strategies\n│   └── flagScoring.ts           # Scoring and ranking logic\n├── knowledge/\n│   └── unleashBestPractices.ts  # Best practices knowledge base\n├── templates/\n│   ├── languages.ts             # Language detection and metadata\n│   ├── wrapperTemplates.ts      # Code wrapping templates\n│   ├── searchGuidance.ts        # Pattern search instructions\n│   └── cleanupGuidance.ts       # Flag cleanup instructions\n└── utils/\n    ├── errors.ts                # Error normalization\n    ├── streaming.ts             # Progress notifications\n    └── stdioLogging.ts          # Stdio protocol traffic logging\n```\n\n### Design principles\n\n- **Thin surface area**: Only the endpoints needed for the core capabilities.\n- **Purpose-driven**: Each module serves a specific, well-defined purpose.\n- **Explicit validation**: Zod schemas validate all inputs before API calls.\n- **Error normalization**: All errors converted to `{code, message, hint}` format.\n- **Progress streaming**: Long-running operations provide visibility.\n- **Best practices integration**: Guidance from Unleash docs embedded in tool descriptions.\n\n## Configuration\n\nThis section provides a quick reference for all configuration options.\n\n**Environment variables:**\n- `UNLEASH_BASE_URL`: Your Unleash instance URL (required). Both `https://your-instance.getunleash.io` and `https://your-instance.getunleash.io/api` are accepted — the server normalizes a trailing `/api` away if present, so you can paste the same value most Unleash SDKs expect.\n- `UNLEASH_PAT`: Personal access token (required).\n- `UNLEASH_DEFAULT_PROJECT`: The default project ID the MCP should use (optional).\n\n**CLI flags:**\n- `--dry-run`: Simulate operations without making actual API calls.\n- `--log-level`: Set logging verbosity (debug, info, warn, error).\n\n## Best practices\n\nThis server encourages Unleash best practices from the [official documentation](https://docs.getunleash.io/topics/feature-flags/best-practices-using-feature-flags-at-scale):\n\n### Flag lifecycle\n\n1. **Create with intent**: Choose the right flag type to signal purpose.\n2. **Document clearly**: Write descriptions that explain the \"why\".\n3. **Plan for cleanup**: Feature flags are temporary; plan their removal.\n4. **Monitor usage**: Enable impression data for important flags.\n\n### Flag types\n\n- **Release flags**: For gradual feature rollouts (remove after full rollout).\n- **Experiment flags**: For A/B tests (remove after analysis).\n- **Operational flags**: For system behavior (longer-lived, review periodically).\n- **Kill switches**: For emergency controls (maintain until feature is stable).\n- **Permission flags**: For access control (longer-lived, review permissions).\n\n### Naming conventions\n\n- Use kebab-case: `new-checkout-flow`\n- Be descriptive: `enable-ai-recommendations` not `flag1`.\n- Include scope when needed: `mobile-push-notifications`.\n\n## API reference\n\nThis server uses the Unleash Admin API. For complete API documentation, see:\n\n- [Unleash Admin API OpenAPI Spec](https://app.unleash-hosted.com/hosted/docs/openapi.json)\n- [Unleash API Documentation](https://docs.getunleash.io/reference/api/unleash)\n\n### Endpoints used\n\n- `GET /api/admin/projects` - List projects\n- `GET /api/admin/projects/{projectId}/features` - List feature flags\n- `POST /api/admin/projects/{projectId}/features` - Create feature flag\n- `GET /api/admin/projects/{projectId}/features/{featureName}` - Get flag details\n- `POST /api/admin/projects/{projectId}/features/{featureName}/environments/{environment}/strategies` - Add rollout strategy\n- `DELETE /api/admin/projects/{projectId}/features/{featureName}/environments/{environment}/strategies/{strategyId}` - Remove strategy\n- `POST /api/admin/projects/{projectId}/features/{featureName}/environments/{environment}/on` - Enable flag\n- `POST /api/admin/projects/{projectId}/features/{featureName}/environments/{environment}/off` - Disable flag\n\n## Troubleshooting\n\n### Configuration issues\n\n**Error: \"UNLEASH_BASE_URL must be a valid URL\"**: Ensure your base URL is complete, including protocol. For example, `https://app.unleash-hosted.com/instance`. Remove any trailing slashes.\n\n**Error: \"UNLEASH_PAT is required\"**: Check that your `.env` file exists and contains `UNLEASH_PAT={{your-personal-access-token}}`. Verify that the token is valid in Unleash.\n\n### API issues\n\n**Error: \"HTTP_401\"**: Your personal access token may be invalid or expired. Generate a new token under **Profile > View Profile settings > Personal API tokens > New token**.\n\n**Error: \"HTTP_403\"**: Your token doesn't have permission to create flags in this project. Review your role and permissions in Unleash.\n\n**Error: \"HTTP_404\"**: The project ID doesn't exist. Confirm the project ID in Unleash Admin UI.\n\n**Error: \"HTTP_409\"**: A flag with this name already exists in the project. Use a different name or reuse the existing flag.\n\n## License\n\nMIT\n\n## Contributing\n\nThis is a purpose-driven project with a focused scope. Contributions should:\n\n- Align with the existing tool surface and MCP resource model.\n- Maintain the thin, purpose-driven architecture.\n- Follow Unleash best practices.\n- Include clear documentation.\n",
  "bytes": 41649,
  "sha": "faf1c165efdd0bccdcd854da8b0190999b35e5a00d2ca27e18eb1786bcbb9f87",
  "repo_slug": "unleash/unleash-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_getunleash_unleash_mcp_aa54eb99/readme"
}