
# Sourcegraph MCP Server

<p className="subtitle">
	Connect AI agents and applications to your Sourcegraph instance's code
	search and analysis capabilities.
</p>

<TierCallout>
	Supported on [Enterprise](/pricing/plans/enterprise) plans.
</TierCallout>

The Sourcegraph Model Context Protocol (MCP) Server provides AI agents and applications with programmatic access to your Sourcegraph instance's code search, navigation, and analysis capabilities through a standardized interface.

## Getting Started

MCP clients that support OAuth can connect directly—just point them at your Sourcegraph instance and authenticate through your browser:

**[Amp](https://ampcode.com/)**

```bash
amp mcp add sg https://sourcegraph.example.com/.api/mcp
```

**[Claude Code](https://www.claude.com/product/claude-code)**

```bash
claude mcp add --transport http sg https://sourcegraph.example.com/.api/mcp
```

This works similarly for other MCP-compatible agents. See [Client Integration](#client-integration) for detailed setup instructions for each client.

## Server Endpoints

The MCP server provides different tool suites for various use cases:

| Endpoint               | Description                     |
| ---------------------- | ------------------------------- |
| `/.api/mcp`            | Full suite of Sourcegraph tools |
| `/.api/mcp/deepsearch` | Deep Search agent               |

Example URL:

```
https://your-sourcegraph-instance.com/.api/mcp
```

## Authentication

The MCP server supports OAuth 2.0 and access token authentication.

### OAuth 2.0

Sourcegraph implements Dynamic Client Registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)), so compatible clients can authenticate automatically without pre-configured client IDs. DCR-registered applications are restricted to the `mcp` scope, which limits access to MCP endpoints only.

<Accordion title="Manual OAuth Setup">

If your agent doesn't support Dynamic Client Registration, you can manually create an OAuth application:

1. Create an OAuth application in your Sourcegraph instance following the instructions [here](/admin/oauth-apps#creating-an-oauth-app). (Note: you can use the `mcp` scope for MCP-only access, or `user:all` for full access)
2. Use `mcp-remote` as a fallback with the following configuration:

```json
{
	"sourcegraph": {
		"type": "stdio",
		"command": "npx",
		"args": [
			"mcp-remote",
			"https://your-sourcegraph-instance.com/.api/mcp",
			"3334",
			"--static-oauth-client-info",
			"{\"client_id\":\"<your-client-id>\"}",
			"--static-oauth-client-metadata",
			"{\"scope\":\"mcp\"}"
		]
	}
}
```

<Callout type="info">
  <ul>
    <li>Replace `your-sourcegraph-instance.com` with your Sourcegraph instance URL and `<your-client-id>` with the ID of the client you registered.</li>
    <li>When using the `mcp-remote` fallback, ensure the OAuth client has one of its redirect URIs set to `http://localhost:3334/oauth/callback`.</li>
  </ul>
</Callout>

</Accordion>

<Accordion title="Disabling Dynamic Client Registration">

To disable DCR while leaving MCP available, set the following site configuration:

```json
{
	"auth.idpDynamicClientRegistrationEnabled": false
}
```

If `mcp.enabled` is `false`, DCR is also unavailable and the registration
endpoint returns `404`.

</Accordion>

### Access Tokens

Alternatively, include a [Sourcegraph access token](/cli/how-tos/creating-an-access-token) in the Authorization header:

```
Authorization: token YOUR_ACCESS_TOKEN
```

<Callout type="info">
	Access tokens can use the `mcp` scope to restrict access to MCP endpoints
	only.
</Callout>

## Availability and Access Control

Admins can control MCP at three levels:

- Site configuration: `mcp.enabled` enables or disables the MCP HTTP endpoints.
- OAuth Dynamic Client Registration: `auth.idpDynamicClientRegistrationEnabled` controls whether OAuth clients can self-register; it is effectively disabled whenever `mcp.enabled` is `false`.
- RBAC: users must have the `MCP#ACCESS` permission to use MCP.

### Site-Level Enablement

Use the `mcp.enabled` site configuration to turn the MCP server on or off for the entire instance:

```json
{
	"mcp.enabled": true
}
```

`mcp.enabled` defaults to `true`. When set to `false`, requests to `/.api/mcp`
and its subpaths return `404 no route`.

### OAuth Dynamic Client Registration

Use `auth.idpDynamicClientRegistrationEnabled` to control whether compatible
OAuth clients can self-register against the Sourcegraph identity provider:

```json
{
	"auth.idpDynamicClientRegistrationEnabled": true
}
```

`auth.idpDynamicClientRegistrationEnabled` defaults to `true`, but it is
treated as `false` whenever `mcp.enabled` is `false`. When DCR is unavailable,
requests to `/.auth/idp/oauth/register` return `404 not found`.

### Restricting MCP with RBAC

When MCP is enabled, Sourcegraph also checks the `MCP#ACCESS` permission before
serving MCP requests. Users without that permission receive `403 forbidden`.

By default, `MCP#ACCESS` is granted to the built-in `User` system role, so all
signed-in users can access MCP unless an admin changes the default role
permissions.

To restrict MCP to a subset of users:

1. Open **Site admin > Users & auth > Roles**.
2. Edit the built-in **User** role and remove the `MCP > ACCESS` permission if you want MCP denied by default.
3. Create a custom role that includes `MCP > ACCESS`.
4. Assign that role to the users who should be allowed to use MCP.

See [Access control](/admin/access-control) for more about managing roles and permissions.

<Callout type="info">
	MCP access control is separate from [repository permissions](/admin/permissions/).
	Users can only read data from repositories they are already allowed to access
	in Sourcegraph.
</Callout>

## Available Tools

<Callout type="info">
	All MCP tools implement result limits to ensure efficient operation and
	prevent context window overflow. These limits are designed to return the
	most relevant results while maintaining optimal performance. For large
	result sets, use pagination parameters (`after`/`before` cursors) where
	available, or refine your search with more specific filters.
</Callout>

The MCP server provides these tools for code exploration and analysis:

### File & Repository Operations

#### `read_file`

Read file contents with line numbers and support for specific ranges and revisions.

**Parameters:**

- `repo` - Repository name (required)
- `path` - File path within repository (required)
- `startLine` - Starting line number (optional)
- `endLine` - Ending line number (optional)
- `revision` - Branch, tag, or commit hash (optional)

**Use cases:** Reading specific files, examining code sections, reviewing different versions

<Callout type="note">
	File size limit is 128KB. Use line ranges for larger files.
</Callout>

#### `list_files`

List files and directories in a repository path.

**Parameters:**

- `repo` - Repository name (required)
- `path` - Directory path (optional, defaults to root)
- `revision` - Branch, tag, or commit hash (optional)

#### `list_repos`

Search and list repositories by name patterns with pagination support.

**Parameters:**

- `query` - Search pattern for repository names (required)
- `limit` - Maximum results per page (optional, default 50)
- `after`/`before` - Pagination cursors (optional)

### Code Search

#### `keyword_search`

Perform exact keyword searches with boolean operators and filters.

**Parameters:**

- `query` - Search query with optional filters (required)

**Supported filters:**

- `repo:` - limit to specific repositories
- `file:` - search specific file patterns
- `rev:` - search specific revisions

**Features:** Boolean AND/OR operators, regex patterns

#### `nls_search`

Semantic search with flexible linguistic matching.

**Parameters:**

- `query` - Natural language search query (required)

**Supported filters:**

- `repo:` - limit to specific repositories
- `file:` - search specific file patterns
- `rev:` - search specific revisions

**Features:** Flexible linguistic matching, stemming, broader results than keyword search

### Code Navigation

#### `go_to_definition`

Find the definition of a symbol from a usage location.

**Parameters:**

- `repo` - Repository name (required)
- `path` - File path containing symbol usage (required)
- `symbol` - Symbol name to find definition for (required)
- `revision` - Branch, tag, or commit hash (optional)

**Features:** Cross-repository support, compiler-level accuracy

#### `find_references`

Find all references to a symbol from its definition location.

**Parameters:**

- `repo` - Repository name (required)
- `path` - File path containing symbol definition (required)
- `symbol` - Symbol name to find references for (required)
- `revision` - Branch, tag, or commit hash (optional)

### Version Control & History

#### `commit_search`

Search commits by message, author, content, files, and date ranges.

**Parameters:**

- `repos` - Array of repository names (required)
- `messageTerms` - Terms to search in commit messages (optional)
- `authors` - Filter by commit authors (optional)
- `contentTerms` - Search in actual code changes (optional)
- `files` - Filter by file paths (optional)
- `after`/`before` - Date range filters (optional)

#### `diff_search`

Search actual code changes for specific patterns across repositories.

**Parameters:**

- `pattern` - Search pattern for code changes (required)
- `repos` - Array of repository names (required)
- `added` - Search only added code (optional)
- `removed` - Search only removed code (optional)
- `author` - Filter by author (optional)
- `after`/`before` - Date range filters (optional)

#### `compare_revisions`

Compare changes between two specific revisions.

**Parameters:**

- `repo` - Repository name (required)
- `base` - Base revision (older version) (required)
- `head` - Head revision (newer version) (required)
- `first` - Maximum file diffs to return (optional, default 50)
- `after` - Pagination cursor (optional)

#### `get_contributor_repos`

Find repositories where a contributor has made commits.

**Parameters:**

- `author` - Author name or email (required)
- `limit` - Maximum repositories to return (optional, default 20)
- `minCommits` - Minimum commits required (optional, default 1)

### Deep Search

<Callout type="info">
	Admins can disable the `deepsearch` tool on the default and v1 MCP endpoints
	by setting the environment variable `SRC_MCP_DISABLE_DEEPSEARCH_TOOL=true`
	on the Sourcegraph instance. This does not affect `deepsearch_read` or the
	dedicated `/deepsearch` endpoint. This is a temporary measure available in
	7.0 and will be replaced by a proper tool allowlist in a future release.
</Callout>

### `deepsearch`

Create a new Deep Search conversation to answer complex questions about your codebase.

**Parameters:**

- `question` - The question to research using Deep Search (required). Should be detailed and specific about what you want to understand.

**Use cases:** Comprehensive analysis of complex technical questions, multi-step research across one or many remote codebases, detailed explanations with supporting evidence, questions that require combining information from multiple sources

#### `deepsearch_read`

Read a Deep Search conversation and return the markdown content of the questions and answers.

**Parameters:**

- `identifier` - The Deep Search conversation identifier (required). Can be:
    - A full Sourcegraph Deep Search URL (e.g., `https://sourcegraph.com/deepsearch/abc123` or `https://sourcegraph.com/deepsearch/shared/abc123`)
    - A read token (e.g., `abc123-def456-...`)

**Use cases:** Reading or re-opening Deep Search results, summarizing existing answers, using past Deep Search as context for new questions

## Best Practices

1. **Repository Scoping:** Use `list_repos` first to find relevant repositories for better performance
2. **Progressive Search:** Start with broad searches (`nls_search`) then narrow with specific tools
3. **File Verification:** Use `list_files` before `read_file` to verify file existence
4. **Pagination:** Use `after`/`before` cursors for large result sets
5. **Tool Combinations:** Chain tools together (e.g., `list_repos` → `commit_search`)
