Skip to content

HTTP and MCP ​

All routes live under the /sourcegraph prefix of the instance's origin. Query routes are under /sourcegraph/v1/ (search is /sourcegraph/api/search), management routes under /sourcegraph/api/admin/, and the MCP endpoint is /sourcegraph/mcp. Both surfaces call the same service, so revisions, limits and error codes are identical. For how to choose a credential see Connecting.

Optional service. Context does not require Source Graph or its MCP server. When neither is installed or configured, Context's query skill still reads code evidence locally through a shallow, sparse partial clone and grep; in its default auto mode it prefers Source Graph only when an authorized instance is available.

Request conventions ​

  • Repository — routes that act on one repository take it as the repo query parameter, owner/repository.
  • Query parameters — only repo and after are accepted, plus revision on /v1/repo/plugins and branch on /api/admin/v1/repo/commit-options. Unknown or repeated parameters return 400 INVALID_QUERY_PARAMETERS.
  • Bodies — JSON objects of at most 64 KiB. Unknown fields, null values, duplicate keys and trailing data are rejected. Query-route fields use capitalized names (Revision, Pattern); management routes use lowercase names (name, policy).
  • Credentials — Authorization: Bearer <service token> or Bearer sgk_… for a personal key; otherwise a browser session or anonymous access. An invalid credential returns 401 and never falls back to anonymous access.
  • Time — each request has a 30-second processing budget; a request that exceeds it returns 503 QUERY_DEADLINE_EXCEEDED, and an unexpected dependency failure returns 503 DEPENDENCY_UNAVAILABLE.

Query routes ​

These are available anonymously when public reading is enabled, and to every credential.

MethodPathBodyReturns
GET/v1/capabilities—Protocol and supported operations
GET/v1/repos— (after for the next page)Registered repositories, 100 per page
GET/v1/repo/availability—One repository: retained versions, heads, groups and jobs, with an ETag
GET/v1/repo/commits—Same as availability
GET/v1/repo/plugins— (optional revision)Repository plugins found at that commit, without running them
POST/v1/repo/resolve{"Revision"}The fixed commit and whether it is indexed
POST/api/search{"Revision","Pattern","FixedStrings","IgnoreCase","Glob","Paths","Output"}Search hits and Meta; see Query Syntax
POST/v1/repo/read{"Revision","Path","StartLine","EndLine"}One file range
POST/v1/repo/list{"Revision","Path","First","After"}Direct children of one directory
POST/v1/repo/diff{"Base","Head","Paths","First","After"}Changed files and patches between two commits

Revision is optional everywhere except diff, where Base and Head are required. read_many has no HTTP route; it exists only as an MCP tool.

Management routes ​

These need the service token or an administrator's browser session. Personal API keys are read-only and get 403 ACCESS_DENIED here. A few read routes — GET /api/admin/v1/repos, GET /api/admin/v1/repo and GET /api/admin/v1/statistics — are also open to anonymous reading.

MethodPathBody or headersPurpose
GET/api/admin/v1/statistics—Request and job statistics
GET/api/admin/v1/instances—Instance heartbeats
GET/api/admin/v1/repos—Repository catalog
POST/api/admin/v1/reposRegistration fields; optional Idempotency-KeyRegister a repository (202)
GET/api/admin/v1/repo—Repository with ETag
PATCH/api/admin/v1/repoUpdate fields; If-Match revisionChange branches, window, visibility, interval, path groups; enable, disable or delete
POST/api/admin/v1/repo/previewUpdate fieldsPreview an update
POST/api/admin/v1/repo/prepare{"kind","commit","group"}; optional Idempotency-KeyQueue sync or index work (202)
GET/api/admin/v1/repo/commit-options— (optional branch)Recent synchronized commits to choose from
POST/api/admin/v1/repo/index/preview, /api/admin/v1/repo/index{"branch","commit"}; the second also preview and If-MatchAdd an index for one commit
POST/api/admin/v1/repo/cleanup/preview, /api/admin/v1/repo/cleanup{"preview"} and If-Match for the secondKeep only the latest index per branch
POST/api/admin/v1/repo/delete/preview, /api/admin/v1/repo/delete{"preview"} and If-Match for the secondPermanently delete repository data
POST/api/admin/v1/repo/jobs/cancel{"job_id"}Cancel a job
POST/api/admin/v1/repo/purgeIf-Match revisionPurge a disabled, deleted repository

Registration fields are listed in Registering Repositories.

Health, sign-in and settings routes ​

PathAccessPurpose
GET /healthzOpenLiveness: {"status":"alive"}
GET /readyzOpenReadiness; 503 when the catalog cannot be read
GET /access-policyOpenpublic_read, public_prepare (always false) and sso_enabled
GET /site-settingsOpenPublic repository defaults
/auth/…BrowserProviders, sign-in and callback, current user, sign-out, api-keys, user administration
/auth/code-credentialsSigned-in sessionYour own Git credentials
/api/admin/settings/…Administrator session onlySite settings sections, code-credentials, query-errors, jobs/clear, storage

Site administration under /api/admin/settings refuses any request that carries an Authorization header — it is reachable only from a signed-in administrator's browser.

MCP endpoint ​

/sourcegraph/mcp speaks stateless Streamable HTTP with JSON responses; the server identifies itself as context-sourcegraph. The toolset depends on the credential:

CredentialTools
Anonymous (public reading on), personal keyRead-only: every tool except prepare
Administrator personal key created with prepare permissionRead-only tools plus prepare, rate-limited to 10 per key and 60 in total per minute
Service tokenAll tools

The optional connection parameter ?plugins= sets the default plugin selection for read and read_many: auto, off, or up to 16 comma-separated names. Invalid values return 400 INVALID_PLUGINS.

MCP tools ​

ToolRequiredOptional (default)
repositories—after
availabilityrepojob_id, include_plugins, revision
resolvereporevision
searchrepo, patternrevision, fixed_strings, ignore_case, glob, paths, output (content or files), max_lines_per_file (10, range 1–1000)
readrepo, pathrevision, start_line (1), end_line (start + 499), plugins
read_manyrepo, files (1–10 items of path, start_line, end_line)revision (resolved once for the batch), plugins
listrepo, first (1–1000)revision, path, after
diffrepo, base, head, first (1–100)paths, after
preparerepo, idempotency_key (8–128 bytes)revision, group

plugins is a list such as [{"name":"context-evidence"}]; [] disables enhancements for that call, and a connection opened with plugins=off always disables them. prepare accepts an omitted revision (default branch), a monitored branch or a full SHA inside the retention window; it is asynchronous, so poll availability afterwards.

MCP output ​

search, read and read_many return readable text rather than raw JSON:

  • search starts with Repository, Commit, Status, Partial, Truncated, a Coverage line, registered Paths and Groups, and the returned and total file counts, then lists each File with numbered matching lines.
  • read starts with Repository, then Path, Commit and Lines: start-end, continuation fields when more remains (Truncated, HasMore, NextStartLine), notes for symlinks, submodules and LFS pointers, then numbered lines N: text.
  • read_many returns one text block per item, each with Item N; RequestedLines, an Error line if that item failed, and the same file header and lines.

Plugin output is appended after the item it belongs to; plugin diagnostics come in a separate block and never replace the original text. The other tools return compact JSON. Errors come back as a tool result marked as an error, whose text is {"code","message"}, with a recovery hint for not-ready states.

Limits ​

LimitValue
Catalog page100 repositories
Search pattern8,192 bytes; cannot match a newline or the empty string
Search globs64, each up to 1,024 bytes
Search or diff paths64 directories
Search page100 files and 1,000 matches with 2 context lines, then smaller fallbacks; 2 MiB response; 5-second deadline
Engine match cap10,000 matches
Read500 lines and 256 KiB per call
read_many1–10 items, 1,000 lines, 256 KiB and 30 seconds shared
List page1–1,000 entries
Diff page1–100 files; patches 64 KiB per file and 256 KiB total
Request body64 KiB

Error format ​

HTTP errors return a JSON body with an Error message and Meta containing Protocol, RequestID, Status, Code and Retryable. Transport-level codes include NOT_FOUND, METHOD_NOT_ALLOWED, INVALID_QUERY_PARAMETERS, INVALID_REQUEST, AUTHENTICATION_REQUIRED, ACCESS_DENIED, RATE_LIMITED, PRECONDITION_REQUIRED, QUERY_DEADLINE_EXCEEDED and DEPENDENCY_UNAVAILABLE. Operation codes such as INDEX_NOT_READY, REVISION_NOT_ELIGIBLE, INVALID_PATTERN or READ_BUDGET_EXCEEDED carry their own status. Operations explains the common ones and what to do about them.

HTTP 与 MCP 接口 ​

所有路由都位于实例源地址的 /sourcegraph 前缀下。查询路由在 /sourcegraph/v1/ 下(搜索为 /sourcegraph/api/search),管理路由在 /sourcegraph/api/admin/ 下,MCP 端点为 /sourcegraph/mcp。两类接口调用的是同一个服务,因此版本、限制和错误码完全一致。如何选择凭据,见接入。

可选服务。 Context 并不依赖 Source Graph 或它的 MCP 服务。两者都没有安装或配置时,Context 的查询技能仍会通过浅层、稀疏的部分克隆加 grep 在本地读取代码证据;默认的 auto 模式只在有可用的已授权实例时才优先使用 Source Graph。

请求约定 ​

  • 仓库:作用于单个仓库的路由通过 repo 查询参数指定仓库,格式为 owner/repository。
  • 查询参数:只接受 repo 和 after,另外 /v1/repo/plugins 接受 revision,/api/admin/v1/repo/commit-options 接受 branch。未知或重复的参数返回 400 INVALID_QUERY_PARAMETERS。
  • 请求体:JSON 对象,最大 64 KiB。未知字段、null 值、重复键和尾随数据都会被拒绝。查询路由的字段名首字母大写(Revision、Pattern);管理路由使用小写字段名(name、policy)。
  • 凭据:使用 Authorization: Bearer <service token>,个人 Key 则为 Bearer sgk_…;否则使用浏览器会话或匿名访问。无效凭据返回 401,绝不会回退为匿名访问。
  • 时间:每个请求有 30 秒的处理预算;超时的请求返回 503 QUERY_DEADLINE_EXCEEDED,意外的依赖故障返回 503 DEPENDENCY_UNAVAILABLE。

查询路由 ​

开启公开读取时,匿名访客可以使用这些路由;所有凭据也都可以使用。

方法路径请求体返回
GET/v1/capabilities—协议与支持的操作
GET/v1/repos—(用 after 翻到下一页)已登记的仓库,每页 100 个
GET/v1/repo/availability—单个仓库:保留的版本、分支最新提交、路径组和任务,附带 ETag
GET/v1/repo/commits—与 availability 相同
GET/v1/repo/plugins—(可选 revision)该提交中发现的仓库插件,不会运行它们
POST/v1/repo/resolve{"Revision"}解析出的固定提交及其是否已建索引
POST/api/search{"Revision","Pattern","FixedStrings","IgnoreCase","Glob","Paths","Output"}搜索命中和 Meta;见搜索语法
POST/v1/repo/read{"Revision","Path","StartLine","EndLine"}一个文件的指定行范围
POST/v1/repo/list{"Revision","Path","First","After"}单个目录的直接子项
POST/v1/repo/diff{"Base","Head","Paths","First","After"}两个提交之间变更的文件与补丁

除 diff 外,Revision 均为可选;diff 必须提供 Base 和 Head。read_many 没有 HTTP 路由,只以 MCP 工具的形式提供。

管理路由 ​

这些路由需要服务令牌或管理员的浏览器会话。个人 API Key 是只读的,在这里会得到 403 ACCESS_DENIED。少数读取路由(GET /api/admin/v1/repos、GET /api/admin/v1/repo 和 GET /api/admin/v1/statistics)也对匿名读取开放。

方法路径请求体或请求头用途
GET/api/admin/v1/statistics—请求与任务统计
GET/api/admin/v1/instances—实例心跳
GET/api/admin/v1/repos—仓库目录
POST/api/admin/v1/repos登记字段;可选 Idempotency-Key登记仓库(202)
GET/api/admin/v1/repo—仓库信息,附带 ETag
PATCH/api/admin/v1/repo更新字段;If-Match 版本修改分支、保留窗口、可见性、同步间隔、路径组;启用、停用或删除
POST/api/admin/v1/repo/preview更新字段预览一次更新
POST/api/admin/v1/repo/prepare{"kind","commit","group"};可选 Idempotency-Key排队执行 sync 或 index 工作(202)
GET/api/admin/v1/repo/commit-options—(可选 branch)可供选择的最近已同步提交
POST/api/admin/v1/repo/index/preview、/api/admin/v1/repo/index{"branch","commit"};后者还需 preview 和 If-Match为某个提交添加索引
POST/api/admin/v1/repo/cleanup/preview、/api/admin/v1/repo/cleanup{"preview"},后者还需 If-Match每个分支只保留最新的索引
POST/api/admin/v1/repo/delete/preview、/api/admin/v1/repo/delete{"preview"},后者还需 If-Match永久删除仓库数据
POST/api/admin/v1/repo/jobs/cancel{"job_id"}取消任务
POST/api/admin/v1/repo/purgeIf-Match 版本清除已停用且已删除的仓库

登记字段见登记仓库。

健康检查、登录与设置路由 ​

路径访问权限用途
GET /healthz开放存活检查:{"status":"alive"}
GET /readyz开放就绪检查;无法读取仓库目录时返回 503
GET /access-policy开放public_read、public_prepare(始终为 false)和 sso_enabled
GET /site-settings开放公开的仓库默认值
/auth/…浏览器登录提供方、登录与回调、当前用户、退出登录、api-keys、用户管理
/auth/code-credentials已登录会话你自己的 Git 凭据
/api/admin/settings/…仅限管理员会话站点设置各分区、code-credentials、query-errors、jobs/clear、storage

/api/admin/settings 下的站点管理会拒绝任何携带 Authorization 请求头的请求,只能从已登录管理员的浏览器访问。

MCP 端点 ​

/sourcegraph/mcp 使用无状态的 Streamable HTTP,响应为 JSON;服务端标识自己为 context-sourcegraph。可用的工具集取决于凭据:

凭据工具
匿名(已开启公开读取)、个人 Key只读:除 prepare 外的全部工具
以 prepare 权限创建的管理员个人 Key只读工具加上 prepare,限流为每个 Key 每分钟 10 次、总计每分钟 60 次
服务令牌全部工具

可选的连接参数 ?plugins= 用于设置 read 和 read_many 的默认插件选择:auto、off,或最多 16 个以逗号分隔的名称。无效值返回 400 INVALID_PLUGINS。

MCP 工具 ​

工具必填可选(默认值)
repositories—after
availabilityrepojob_id、include_plugins、revision
resolvereporevision
searchrepo、patternrevision、fixed_strings、ignore_case、glob、paths、output(content 或 files)、max_lines_per_file(10,范围 1–1000)
readrepo、pathrevision、start_line(1)、end_line(起始行 + 499)、plugins
read_manyrepo、files(1–10 项,每项含 path、start_line、end_line)revision(整批只解析一次)、plugins
listrepo、first(1–1000)revision、path、after
diffrepo、base、head、first(1–100)paths、after
preparerepo、idempotency_key(8–128 字节)revision、group

plugins 是一个列表,例如 [{"name":"context-evidence"}];传 [] 会在本次调用中关闭增强,而以 plugins=off 打开的连接始终关闭增强。prepare 接受省略版本(默认分支)、监控分支,或保留窗口内的完整 SHA;它是异步的,之后请轮询 availability。

MCP 输出 ​

search、read 和 read_many 返回可读文本,而不是原始 JSON:

  • search 依次以 Repository、Commit、Status、Partial、Truncated、一行 Coverage、已登记的 Paths 和 Groups,以及返回文件数与总文件数开头,然后列出每个 File 及其带行号的匹配行。
  • read 以 Repository 开头,接着是 Path、Commit 和 Lines: start-end;还有剩余内容时给出续读字段(Truncated、HasMore、NextStartLine),并附上符号链接、子模块和 LFS 指针的说明,最后是 N: text 格式的带行号内容。
  • read_many 为每一项返回一个文本块,每块包含 Item N; RequestedLines,该项失败时有一行 Error,其余为相同的文件头和内容行。

插件输出追加在所属项之后;插件诊断信息放在单独的块中,绝不会替换原始文本。其他工具返回紧凑的 JSON。错误以标记为错误的工具结果返回,其文本为 {"code","message"},未就绪状态会附带恢复提示。

限制 ​

限制项值
仓库目录分页100 个仓库
搜索模式8,192 字节;不能匹配换行符或空字符串
搜索 glob64 个,每个最多 1,024 字节
搜索或差异路径64 个目录
搜索分页100 个文件、1,000 条匹配,带 2 行上下文,超出时逐级缩小;响应 2 MiB;截止时间 5 秒
引擎匹配上限10,000 条匹配
读取每次调用 500 行、256 KiB
read_many1–10 项,共享 1,000 行、256 KiB 和 30 秒
列目录分页1–1,000 个条目
差异分页1–100 个文件;补丁每个文件 64 KiB,总计 256 KiB
请求体64 KiB

错误格式 ​

HTTP 错误返回一个 JSON 体,其中包含 Error 消息,以及含有 Protocol、RequestID、Status、Code 和 Retryable 的 Meta。传输层错误码包括 NOT_FOUND、METHOD_NOT_ALLOWED、INVALID_QUERY_PARAMETERS、INVALID_REQUEST、AUTHENTICATION_REQUIRED、ACCESS_DENIED、RATE_LIMITED、PRECONDITION_REQUIRED、QUERY_DEADLINE_EXCEEDED 和 DEPENDENCY_UNAVAILABLE。INDEX_NOT_READY、REVISION_NOT_ELIGIBLE、INVALID_PATTERN 或 READ_BUDGET_EXCEEDED 等操作错误码有各自的状态码。运维解释了常见错误码及处理方法。