Skip to content

MCP 层(cmd/mcp-server/)

MCP(Model Context Protocol)层把 SDK 方法包装成 AI 可调用的结构化工具。一个工具 = 一个 SDK 方法 + 输入 schema + 结果格式化。

cmd/mcp-server 20 工具 stdio/SSE/HTTP

入口与传输

main.goflag 选传输模式:

bash
mcp-server --transport stdio          # 本地 AI 客户端(默认)
mcp-server --transport sse --addr :8080 --base-url https://my.host
mcp-server --transport http --addr :8080
flowchart LR A[AI 客户端] -->|stdio/sse/http| SRV[MCP Server] SRV --> RT[registerTools
注册 20 个工具] RT --> CL[共享 crtsh.Client] CL --> CRT[crt.sh]

三种传输都基于 mark3labs/mcp-go。SSE/HTTP 模式带优雅关停(SIGINT/SIGTERM)。

工具注册模式

tools.goregisterTools(s, client) 为每个 SDK方法注册一个工具:

go
searchTool := mcp.NewTool("search_certificates",
    mcp.WithDescription("Search CT logs by domain, SHA-256, serial..."),
    mcp.WithString("query", mcp.Required(), mcp.Description("...")),
    mcp.WithBoolean("exclude_expired", ...),
    // ...
)
s.AddTool(searchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    params := mapToolParamsToQueryParams(req)  // 薄映射
    certs, pagination, err := client.SearchCertificates(ctx, params)
    return formatResult(certs, pagination, err)
})

工具处理函数只做三件事:参数映射 → 调 SDK → 格式化输出。没有业务逻辑。

20 个工具一览

工具SDK 方法
search_certificatesSearchCertificates
export_search_jsonFetchSearchJSON
export_search_csvFetchSearchCSV
export_search_atomFetchSearchAtomFeed
get_certificateGetCertificateByID
get_ct_entryFetchCTEntryByID
get_atom_feedFetchAtomFeed
get_raw_certificateFetchRawCertificate
generate_add_chainGenerateAddChainJSON
get_asn1_viewFetchASN1View
get_hierarchy_viewFetchHierarchyView
get_graph_viewFetchGraphView
get_path_validation_viewFetchPathValidationView
get_advanced_search_pageFetchAdvancedSearchPage
get_cert_populationsFetchCertificatePopulations
get_info_pageFetchInfoPage
get_caFetchCAByID
get_issuer_certificatesFetchIssuerCertificatesByCAID
search_censysBuildCensysURL
list_supported_optionsregistry 辅助函数 + InfoPages

设计要点

  • 共享一个 crtsh.Client:所有工具复用同一个底层 client,连接池/超时/重试统一
  • schema 严格:每个工具的参数有类型、描述、required,AI 据此正确填参
  • 错误透传:SDK 的 typed error 被翻译成工具调用错误返回给 AI,AI 能区分"没找到"和"限流"
  • list_supported_options:把 SearchTypes()MatchModes() 等注册表暴露给 AI,让 AI 自己发现合法选项,而不是靠硬编码

下一层:CLI 层