Skip to content

Connecting Agents, Scripts and the CLI to Source Graph ​

Connecting gives your Agent, script or terminal code search and reading at a pinned commit, without cloning the repository first. Most Context users need only one thing: connect their Agent over MCP, as described in the next section, so the Agent can read the code behind an answer remotely. What Is Source Graph explains why that matters, when you need it and how to try the live demo.

Every Source Graph instance serves four entry points under the /sourcegraph/ path of its origin. Pick the one that fits the caller; all of them run the same operations with the same rules, except that only MCP reads several ranges in one call and the CLI has no command for listing branches and tags.

CallerEntry point
A personThe website at /sourcegraph/ — search, code reading, repositories and the Connect page
An AI Agent or MCP client/sourcegraph/mcp — Streamable HTTP, stateless, JSON responses
A script or serviceThe HTTP API — /sourcegraph/v1/… for repository reads and /sourcegraph/api/search for search
A terminalsourcegraph-cli, a small HTTP client for the same routes

The website's Connect page always shows ready-to-copy configuration for the instance you are on, including the right address and whether a token is needed. Prefer it over hand-written examples when they differ.

Connect your Agent for Context ​

  1. If the instance needs a credential, sign in and create a personal API key (see Choose a credential). The public demo needs none.
  2. Open the site's Connect page and copy the configuration for your Agent host; it shows the equivalent command or file for Claude Code, Codex and Cursor.
  3. Keep the server name context-sourcegraph. That is the name Context's query Skill looks for when it reads cited code, as described in Choose how Context reads code.

For any other client that supports Streamable HTTP, point it at the /mcp endpoint. For the public demo:

json
{
  "mcpServers": {
    "context-sourcegraph": {
      "type": "http",
      "url": "https://context4ai.org/sourcegraph/mcp?plugins=auto"
    }
  }
}

For an instance that needs a credential, add "headers": { "Authorization": "Bearer <token>" }. The optional plugins query parameter controls repository plugins for the whole connection: auto (default selection), off, or up to 16 comma-separated plugin names. Anonymous connections get the read-only tools. A personal key gets prepare as well when its owner is an administrator or manages at least one repository, and the service token gets every tool. Use MCP tool discovery for the current input schemas — the HTTP and MCP reference lists them.

Choose how Context reads code ​

Once the server context-sourcegraph is connected, Context uses it to read cited code. By default your Agent reuses suitable local material and otherwise prefers Source Graph before any local checkout. To change that, ask in the conversation to read only through Source Graph or only locally, such as "work offline"; an explicit request always wins. For a Knowledge Bot, set the mode in the Bot's prompt.

The instance must cover the knowledge workspace and every source repository its answers rely on; if one is missing, see Missing a repository?. What this gives your answers is described in What Is Source Graph.

Missing a repository? ​

If search or reading cannot find a repository you need, either it is not registered on that instance yet, or it is a private repository your credential cannot see; both answer REPOSITORY_NOT_FOUND. A private repository is visible only to its creator, its managers and administrators, so ask one of them to add you as a manager. If you try to register a name that already exists, the website tells you who registered it so you know whom to ask. A repository that is not registered yet needs an administrator, or any signed-in user when the site allows user registration, and a private code-hosting repository also needs a token for its code source so the service can fetch it. On your own instance, register it as described in Registering and Managing Repositories.

Choose a credential ​

CredentialHow to get itWhat it allows
None (anonymous)—Read-only access to public repositories, when the site allows public reading; rate-limited per client
Personal API key (sgk_…)Sign in, open your user settings and create an API tokenReads public repositories and the private repositories you created or manage, over HTTP or MCP; an administrator's key is not widened to every repository. It can also request indexing for repositories you manage, or for any repository it can see when you are an administrator
Service tokenThe instance's service credential, at least 32 characters. SOURCEGRAPH_API_TOKEN seeds it on first start (it is generated when unset); afterwards the value saved in the database is usedEvery HTTP and MCP operation on every repository, including registration and indexing — for automation you control

Send keys and tokens as Authorization: Bearer <value>. An invalid credential is rejected with AUTHENTICATION_REQUIRED; it never falls back to anonymous access. Keep credentials in your client's secret store or environment, never in shared configuration files. Ops: Sign-in and Permissions explains each mode in detail.

Choose the version to read ​

Search, read, list and diff work at a monitored branch — one the instance keeps synchronized, as listed by repositories — or at a full 40-character commit SHA. Omitting the revision uses the default branch at its last synchronized head. Any other branch, and every tag, is turned into a full commit first:

  1. Find it with refs when you do not know its exact name. refs lists the repository's branches or tags from its remote, newest first, each with its commit, created_at, author, title, and whether it is monitored and indexed. Narrow the list with kind (branch, the default, tag or all), query (part of the name), author, title, since and until; sort by name instead of creation time; and page with first (1–100) and the returned next_cursor as after.
  2. Resolve it with resolve. It accepts any branch or tag name of a registered repository, as well as refs/heads/<name> and refs/tags/<name>, and returns the full commit, whether that commit is indexed, and how it was found in source: observed for a monitored branch, which resolves to its last synchronized head and can lag the remote, and catalog or remote for other branches and tags.
  3. Read at that SHA with search, read, list or diff. When indexed is false, the commit must be prepared first: a repository manager prepares that full SHA — or this connection itself, if its tools include prepare — and the Agent reads at it once availability shows it ready. Listing and resolving never download code or build an index.

Branch and tag names are case-sensitive. A bare name that is both a branch and a tag answers REF_AMBIGUOUS; pass refs/heads/<name> or refs/tags/<name> instead. REF_NOT_FOUND means there is no such branch or tag, and REF_NOT_COMMIT that a tag does not point to a commit. Short SHAs, HEAD and revision expressions are not accepted, and an unmonitored branch name passed straight to search or read answers BRANCH_NOT_MONITORED. The first listing of a large repository can answer REFS_CATALOG_PREPARING; retry after its Retry-After interval, or resolve a complete name meanwhile.

Call the HTTP API ​

Every repository-specific request names the repository with the repo query parameter, as owner/repository. Request bodies are JSON objects with capitalized field names; unknown fields are rejected.

bash
# Search at the default branch head
curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Pattern":"timeout","IgnoreCase":true,"Paths":["packages"]}'

# Read lines at the commit returned in Meta.Commit
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/read?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"<commit>","Path":"README.md","StartLine":1,"EndLine":40}'

# Find the ten newest tags created since 1 October 2026
curl -s 'https://context4ai.org/sourcegraph/v1/repo/refs?repo=context4ai/context&kind=tag&since=2026-10-01&first=10'

# Resolve a tag to its full commit and check whether it is indexed
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/resolve?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"refs/tags/v0.7.95"}'

refs takes its filters as query parameters (kind, query, author, title, since, until, sort, first and after), each at most once. read_many is available only over MCP; over HTTP, issue several read calls.

Use the command-line client ​

sourcegraph-cli is built with the service and reads two environment variables: SOURCEGRAPH_URL, the instance's /sourcegraph base address (default https://context4ai.org/sourcegraph, and it must be HTTPS), and the optional SOURCEGRAPH_API_TOKEN. Search flags follow rg:

bash
export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph"
sourcegraph-cli search -repo context4ai/context -g '*.ts' 'OnboardingVersion' packages
sourcegraph-cli read -repo context4ai/context -revision <commit> \
  -path README.md -start-line 1 -end-line 40

resolve accepts the same branch, tag and refs/heads/ or refs/tags/ forms as the HTTP route, while the other commands take a monitored branch or a full SHA. The CLI has no refs command; find branches and tags through the HTTP route or the MCP tool. It prints the raw JSON response and exits with 3 when a request is accepted but not ready yet. All commands and flags are in the CLI reference.

The search-then-read loop ​

Agents get the most from Source Graph with a short loop:

  1. Search the repository. Omit the revision to use its default branch head, or pass a monitored branch or a full commit you already know; for another branch or a tag, resolve it first as described in Choose the version to read.
  2. Pin the commit returned in the result's metadata.
  3. Read the decisive ranges at that commit — directly when the file is known, several at once with read_many. Keep the repository, full commit SHA and path together for each range, use paths returned by search or list, and group a read_many call by repository and commit; end_line is an absolute line number, not a count.
  4. Continue from the returned next line if the file goes on, and treat Partial, Truncated and coverage flags as limits, not as proof that something is absent.

List repositories, look up branches and tags, or resolve the revision only when the repository or version is unknown or a request fails, not before every query. If a request fails — for example 409 INDEX_NOT_READY when a commit has not been indexed yet — look up the code in Ops: Day-to-Day Operations for what it means and what to do.

连接 Agent、脚本和命令行使用 Source Graph ​

接入后,你的 Agent、脚本或终端无需先克隆仓库,就能在固定提交上搜索和阅读代码。大多数 Context 用户只需要做一件事:按下一节所述通过 MCP 接入自己的 Agent,让 Agent 能远程读取回答背后的代码。为什么这很重要、什么时候需要它,以及如何试用在线演示,见 Source Graph 是什么。

每个 Source Graph 实例都在其源站的 /sourcegraph/ 路径下提供四个入口。按调用方选择合适的入口即可;它们执行相同的操作,遵循相同的规则,只是一次调用读取多段代码仅 MCP 支持,而 CLI 没有列出分支和标签的命令。

调用方入口
人位于 /sourcegraph/ 的网站:搜索、代码阅读、仓库以及 Connect(接入)页面
AI Agent 或 MCP 客户端/sourcegraph/mcp:Streamable HTTP,无状态,返回 JSON
脚本或服务HTTP API:仓库读取使用 /sourcegraph/v1/…,搜索使用 /sourcegraph/api/search
终端sourcegraph-cli,一个调用相同路由的小型 HTTP 客户端

网站的 Connect 页面始终会展示当前实例可直接复制的配置,包括正确的地址以及是否需要令牌。当它与手写示例不一致时,以该页面为准。

为 Context 接入你的 Agent ​

  1. 如果实例需要凭据,请登录并创建个人 API Key(见 选择凭据)。公开演示实例不需要凭据。
  2. 打开站点的 Connect 页面,复制适用于你的 Agent 宿主的配置;页面会展示 Claude Code、Codex 和 Cursor 对应的命令或配置文件。
  3. 保持服务器名称为 context-sourcegraph。Context 的查询 Skill 读取被引用的代码时,查找的就是这个名称,详见 选择 Context 读取代码的方式。

对于其他支持 Streamable HTTP 的客户端,将其指向 /mcp 端点。公开演示实例的配置如下:

json
{
  "mcpServers": {
    "context-sourcegraph": {
      "type": "http",
      "url": "https://context4ai.org/sourcegraph/mcp?plugins=auto"
    }
  }
}

如果实例需要凭据,添加 "headers": { "Authorization": "Bearer <token>" }。可选的 plugins 查询参数控制整个连接使用的仓库插件:auto(默认选择)、off,或最多 16 个以逗号分隔的插件名称。匿名连接只能获得只读工具。个人 Key 的所有者是管理员或至少管理一个仓库时,该 Key 还能获得 prepare;服务令牌可以使用所有工具。当前的输入 schema 请通过 MCP 工具发现获取,HTTP 与 MCP 接口 参考文档中列出了这些工具。

选择 Context 读取代码的方式 ​

接入服务器 context-sourcegraph 后,Context 会用它读取被引用的代码。默认情况下,Agent 会复用合适的本地材料,否则优先使用 Source Graph,其次才是本地检出。要改变这一点,可以在对话中要求只通过 Source Graph 读取或只在本地读取,例如“离线工作”;明确的要求始终优先。对于知识 Bot,请在 Bot 的提示词中设置读取方式。

实例必须覆盖知识工作区以及回答所依赖的每个源码仓库;如果缺少某个仓库,见 缺少某个仓库?。这能为你的回答带来什么,见 Source Graph 是什么。

缺少某个仓库? ​

如果搜索或读取找不到你需要的仓库,要么它还没有在该实例上登记,要么它是你的凭据看不到的私有仓库;这两种情况都返回 REPOSITORY_NOT_FOUND。私有仓库只对其创建者、管理者和管理员可见,因此请联系其中一位,请对方把你添加为管理者。如果你尝试登记一个已存在的名称,网站会告诉你是谁登记的,让你知道该找谁。尚未登记的仓库需要管理员来登记;如果站点允许用户登记仓库,任何已登录用户也可以登记。代码托管平台上的私有仓库还需要其代码来源的令牌,服务才能拉取它。如果是你自己的实例,按 登记和管理仓库 中的说明登记即可。

选择凭据 ​

凭据获取方式允许的操作
无(匿名)—当站点允许公开读取时,只读访问公开仓库;按客户端限流
个人 API Key(sgk_…)登录后打开用户设置,创建 API 令牌通过 HTTP 或 MCP 读取公开仓库以及你创建或管理的私有仓库;管理员的 Key 不会扩展到所有仓库。它还可以为你管理的仓库请求建索引;当你是管理员时,可以为它能看到的任何仓库请求建索引
服务令牌实例的服务凭据,至少 32 个字符。SOURCEGRAPH_API_TOKEN 在首次启动时提供初始值(未设置时自动生成);之后使用保存在数据库中的值对所有仓库执行所有 HTTP 和 MCP 操作,包括登记和建索引,适用于你自己掌控的自动化流程

以 Authorization: Bearer <value> 的形式发送 Key 和令牌。无效凭据会被拒绝并返回 AUTHENTICATION_REQUIRED,绝不会回退为匿名访问。请将凭据保存在客户端的密钥存储或环境变量中,不要放进共享的配置文件。各模式的详细说明见 运维:登录与权限。

选择要读取的版本 ​

搜索、读取、列目录和差异比较都在监控分支(实例保持同步的分支,由 repositories 列出)或 40 位完整提交 SHA 上进行。省略 revision 时使用默认分支最近一次同步的最新提交。其他任何分支以及所有标签,都要先转换为完整提交:

  1. 用 refs 查找:不知道确切名称时使用。refs 从远端列出仓库的分支或标签,最新的在前,每项都带有提交、created_at、作者、标题,以及是否被监控、是否已建索引。可以用 kind(默认 branch,也可以是 tag 或 all)、query(名称的一部分)、author、title、since 和 until 缩小范围;可以按 name 而不是创建时间排序;用 first(1–100)分页,并把返回的 next_cursor 作为 after 传入。
  2. 用 resolve 解析:它接受已登记仓库的任意分支名或标签名,以及 refs/heads/<name> 和 refs/tags/<name>,返回完整的 commit、该提交是否已建索引(indexed),并在 source 中说明它是如何找到的:监控分支为 observed,解析到其最近一次同步的最新提交,可能落后于远端;其他分支和标签为 catalog 或 remote。
  3. 在该 SHA 上读取:使用搜索、读取、列目录或差异比较。indexed 为 false 时,需要先准备该提交:由仓库管理者准备这个完整 SHA(如果当前连接的工具包含 prepare,也可以由它自己准备),等 availability 显示就绪后,Agent 再在该提交上读取。列出和解析从不下载代码,也不建索引。

分支名和标签名区分大小写。同时是分支和标签的裸名称会返回 REF_AMBIGUOUS;请改传 refs/heads/<name> 或 refs/tags/<name>。REF_NOT_FOUND 表示不存在该分支或标签,REF_NOT_COMMIT 表示标签没有指向提交。不接受短 SHA、HEAD 和版本表达式;把未被监控的分支名直接传给搜索或读取会返回 BRANCH_NOT_MONITORED。大型仓库首次列出时可能返回 REFS_CATALOG_PREPARING;请在 Retry-After 间隔之后重试,或在此期间解析完整名称。

调用 HTTP API ​

每个针对具体仓库的请求都通过 repo 查询参数指定仓库,格式为 owner/repository。请求体是字段名首字母大写的 JSON 对象,未知字段会被拒绝。

bash
# Search at the default branch head
curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Pattern":"timeout","IgnoreCase":true,"Paths":["packages"]}'

# Read lines at the commit returned in Meta.Commit
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/read?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"<commit>","Path":"README.md","StartLine":1,"EndLine":40}'

# Find the ten newest tags created since 1 October 2026
curl -s 'https://context4ai.org/sourcegraph/v1/repo/refs?repo=context4ai/context&kind=tag&since=2026-10-01&first=10'

# Resolve a tag to its full commit and check whether it is indexed
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/resolve?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"refs/tags/v0.7.95"}'

refs 通过查询参数接收过滤条件(kind、query、author、title、since、until、sort、first 和 after),每个参数最多出现一次。read_many 只能通过 MCP 使用;通过 HTTP 时,请发起多次 read 调用。

使用命令行客户端 ​

sourcegraph-cli 随服务一同构建,读取两个环境变量:SOURCEGRAPH_URL 是实例的 /sourcegraph 基础地址(默认 https://context4ai.org/sourcegraph,必须是 HTTPS);SOURCEGRAPH_API_TOKEN 可选。搜索参数沿用 rg 的风格:

bash
export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph"
sourcegraph-cli search -repo context4ai/context -g '*.ts' 'OnboardingVersion' packages
sourcegraph-cli read -repo context4ai/context -revision <commit> \
  -path README.md -start-line 1 -end-line 40

resolve 接受与 HTTP 路由相同的分支、标签以及 refs/heads/ 或 refs/tags/ 形式,其他命令则接受监控分支或完整 SHA。CLI 没有 refs 命令;请通过 HTTP 路由或 MCP 工具查找分支和标签。它会输出原始 JSON 响应;当请求已被接受但尚未就绪时,以 3 退出。所有命令和参数见 CLI 参考文档。

先搜索、再读取的循环 ​

Agent 用一个简短的循环就能充分利用 Source Graph:

  1. 搜索仓库。省略 revision 时使用默认分支的最新提交,也可以传入监控分支或已知的完整提交;对于其他分支或标签,先按 选择要读取的版本 中的说明解析。
  2. 固定提交:记下结果元数据中返回的提交。
  3. 在该提交上读取关键范围:已知文件时直接读取,需要多处时用 read_many 一次读取。每个范围都要同时保留仓库、完整提交 SHA 和路径,使用 search 或 list 返回的路径,并按仓库和提交对 read_many 调用分组;end_line 是绝对行号,而不是行数。
  4. 如果文件还有后续内容,从返回的下一行继续读取;将 Partial、Truncated 和覆盖范围标记视为限制,而不是内容不存在的证明。

无需在每次查询前都列出仓库、查找分支和标签或解析 revision;只有在仓库或版本未知、或请求失败时才这样做。如果请求失败——例如某个提交尚未建好索引时返回 409 INDEX_NOT_READY——请在 运维:日常运维与排障 中查找该错误码的含义和处理方法。