Metadata-Version: 2.5
Name: atengk-mcp-server-api-client
Version: 0.1.0
Summary: 面向 AI Agent 的零配置通用 API 联调客户端 MCP Server：支持 HTTP/HTTPS、GraphQL、命名内存会话 ApiSession、SSE 流式响应与 WebSocket 全双工通信
Project-URL: Homepage, https://github.com/atengk/mcp-server-api-client
Project-URL: Repository, https://github.com/atengk/mcp-server-api-client.git
Project-URL: Issues, https://github.com/atengk/mcp-server-api-client/issues
Project-URL: Documentation, https://github.com/atengk/mcp-server-api-client#readme
Project-URL: PyPI, https://pypi.org/project/atengk-mcp-server-api-client/
Author: Ateng
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Ateng (atengk)
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: api-client,graphql,http,mcp,model-context-protocol,rest,sse,websocket
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27.0
Requires-Dist: mcp>=2.0.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: websockets>=14.0
Description-Content-Type: text/markdown

# atengk-mcp-server-api-client

<p align="center">
  <strong>面向 AI Agent 的零配置通用 API 联调客户端 MCP Server（HTTP/HTTPS、GraphQL、命名内存会话 ApiSession、SSE 流式响应与 WebSocket 全双工通信）</strong>
</p>

<p align="center">
  <a href="https://pypi.org/project/atengk-mcp-server-api-client/">
    <img src="https://img.shields.io/pypi/v/atengk-mcp-server-api-client?logo=pypi&amp;logoColor=white&amp;style=flat-square" alt="PyPI Version" />
  </a>
  <a href="https://pypi.org/project/atengk-mcp-server-api-client/">
    <img src="https://img.shields.io/pypi/pyversions/atengk-mcp-server-api-client?logo=python&amp;logoColor=white&amp;style=flat-square" alt="Python Versions" />
  </a>
  <a href="https://github.com/atengk/mcp-server-api-client/actions/workflows/ci.yml">
    <img src="https://img.shields.io/github/actions/workflow/status/atengk/mcp-server-api-client/ci.yml?branch=main&amp;label=CI&amp;style=flat-square" alt="CI Status" />
  </a>
  <a href="https://github.com/atengk/mcp-server-api-client/releases">
    <img src="https://img.shields.io/github/v/release/atengk/mcp-server-api-client?style=flat-square" alt="Release" />
  </a>
  <a href="./LICENSE">
    <img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=flat-square" alt="License" />
  </a>
  <a href="./CONTRIBUTING.md">
    <img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square" alt="PRs Welcome" />
  </a>
</p>

---

## 📖 项目简介

`atengk-mcp-server-api-client` 是一款面向 AI Agent / LLM 的 Model Context Protocol (MCP) API 客户端服务端，基于 **Python 3.11+ + MCP Python SDK v2 (`MCPServer`) + `httpx` + Pydantic v2** 构建。

### 当前基线与演进规划
- **当前基线（`v0.1.0` 已落地全栈 16 工具）**：已完成标准化开源工程底座、CI/CD 质量门禁、提交/发版守卫、`ServerConfig` 运行时配置、`--check` 环境自检探针、`http_request`、命名 `ApiSession`、`sse_*` 流式工具及 `ws_*` 全双工 WebSocket 工具。
- **核心能力矩阵（16 个正交工具）**：
  - **HTTP / HTTPS (`http_request`)**：基于 `httpx.AsyncClient` 的异步 HTTP/REST/GraphQL 请求执行、文件上传/落盘、光栅图 `ImageContent` 内联、轻量 JSONPath 提取与大文本自动截断落盘（遵循 ADR-0001 与 ADR-0002）；
  - **命名内存会话 (`session_*`)**：基于 `ApiSession` 维护隔离 `CookieJar`、基础地址、默认请求头与默认网络参数，并跨 HTTP/SSE/WebSocket 复用；
  - **SSE 流式响应 (`sse_*`)**：支持 `GET`/`POST` 单次聚合与后台 `SseSubscription` 环形缓冲游标增量读取；
  - **WebSocket 全双工 (`ws_*`)**：基于 `websockets` 的一次性短交互与后台 `WsConnection` 长连接池（支持 `text`/`json`/`hex` 帧收发）。

---

## 🛠️ 快速开始

### 1. 环境准备
请确保本地已安装：
- **Python**：`>= 3.11`
- **uv**：Python 包与虚拟环境管理工具

### 2. 安装与运行（源码 / PyPI / Docker）

```bash
# 方式 A：源码本地开发与校验
git clone https://github.com/atengk/mcp-server-api-client.git
cd mcp-server-api-client
git config core.hooksPath .githooks
uv sync --all-extras --dev

# 查看版本与参数帮助，运行规范与测试门禁
uv run mcp-server-api-client --version
uv run mcp-server-api-client --help
uv run ruff check . && uv run ruff format --check . && uv run pytest

# 方式 B：PyPI 免安装或全局安装
uvx --from atengk-mcp-server-api-client mcp-server-api-client --help
pip install atengk-mcp-server-api-client

# 方式 C：本地构建或拉取 GHCR 非 root 多架构 Docker 镜像运行
docker pull ghcr.io/atengk/mcp-server-api-client:latest
docker build -t mcp-server-api-client .
docker run --rm -i mcp-server-api-client --check
docker run -d --name mcp-api-client -p 8000:8000 mcp-server-api-client \
  --transport streamable-http --host 0.0.0.0 --port 8000 --auth-token YOUR_API_TOKEN
```

### 3. MCP 客户端接入配置（`stdio` / `streamable-http` / `sse`）

#### 方式 A：本地 `stdio` 进程模式（Claude Desktop / Cursor / Antigravity）

```json
{
  "mcpServers": {
    "api-client": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/mcp-server-api-client",
        "run",
        "mcp-server-api-client"
      ]
    }
  }
}
```

若使用 Docker 容器以 `stdio` 模式隔离运行：

```json
{
  "mcpServers": {
    "api-client-docker": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "mcp-server-api-client"
      ]
    }
  }
}
```

#### 方式 B：远端 `streamable-http` 模式（`/mcp`，推荐配合 `--auth-token`）

```json
{
  "mcpServers": {
    "api-client-remote": {
      "type": "streamable-http",
      "url": "http://127.0.0.1:8000/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_API_TOKEN"
      }
    }
  }
}
```

#### 方式 C：远端兼容 `sse` 模式（`/sse`，配合 `--auth-token`）

```json
{
  "mcpServers": {
    "api-client-sse": {
      "type": "sse",
      "url": "http://127.0.0.1:8000/sse",
      "headers": {
        "Authorization": "Bearer YOUR_API_TOKEN"
      }
    }
  }
}
```

### 4. 环境自检探针 (`--check` / `--doctor`)

在首次部署或怀疑运行环境缺失依赖/权限异常时，可通过自检命令一次性核验 Python 版本、核心依赖与临时落盘目录状态（退出码 `0` 表示就绪，非 `0` 表示存在异常）：

<!-- Tested-By: tests/test_config_and_doctor.py#test_doctor_check_reports_healthy_json_and_zero_exit -->
```bash
uv run mcp-server-api-client --check
```

预期输出示例（实际 `temp_dir.path` 随当前操作系统临时目录变化）：

<!-- Tested-By: tests/test_config_and_doctor.py#test_doctor_check_reports_healthy_json_and_zero_exit -->
```json
{
  "status": "ok",
  "exit_code": 0,
  "python": {
    "ok": true,
    "version": "3.12.14",
    "minimum": "3.11"
  },
  "dependencies": {
    "ok": true,
    "packages": {
      "mcp": { "ok": true, "version": "2.3.0", "error": null },
      "httpx": { "ok": true, "version": "0.29.0", "error": null },
      "websockets": { "ok": true, "version": "17.4", "error": null },
      "pydantic": { "ok": true, "version": "2.14.4", "error": null }
    }
  },
  "temp_dir": {
    "ok": true,
    "path": "<OS_TEMP>/mcp-server-api-client",
    "error": null
  }
}
```

### 5. CLI 参数、环境变量与远端鉴权

服务端遵循 **零配置开箱即用**，所有运行期参数均可选；生效优先级为 **`CLI 参数 > MCP_API_CLIENT_* 环境变量 > 内置默认值`**。

#### CLI 启动选项

| 参数 | 环境变量 | 默认值 | 说明 |
| :--- | :--- | :--- | :--- |
| `-t`, `--transport` | `MCP_API_CLIENT_TRANSPORT` | `stdio` | 传输协议：`stdio`、`sse` 或 `streamable-http` |
| `--host` | `MCP_API_CLIENT_HOST` | `127.0.0.1` | 远端模式绑定监听地址 |
| `-p`, `--port` | `MCP_API_CLIENT_PORT` | `8000` | 远端模式绑定监听端口（`1-65535`） |
| `--auth-token` | `MCP_API_CLIENT_AUTH_TOKEN` | 无 | 远端 `sse`/`streamable-http` 端点 Bearer 鉴权令牌 |
| `--log-level` | `MCP_API_CLIENT_LOG_LEVEL` | `INFO` | 日志级别（`DEBUG`/`INFO`/`WARNING`/`ERROR`，严格输出到 `stderr`） |
| `--check`, `--doctor` | — | `false` | 执行环境自检探针并向 `stdout` 输出 JSON 后退出 |
| `-v`, `--version` | — | `false` | 输出当前版本号并退出 |

#### 池化与响应边界环境变量

| 环境变量 | 默认值 | 说明 |
| :--- | :--- | :--- |
| `MCP_API_CLIENT_MAX_SSE_CONNECTIONS` | `20` | `SseSubscription` 后台订阅池活跃上限 |
| `MCP_API_CLIENT_MAX_WS_CONNECTIONS` | `20` | `WsConnection` 后台连接池活跃上限 |
| `MCP_API_CLIENT_RING_BUFFER_SIZE` | `200` | 单个后台连接保留的环形缓冲条目上限 |
| `MCP_API_CLIENT_IDLE_TIMEOUT_SECONDS` | `600.0` | 后台连接空闲自动回收秒数 |
| `MCP_API_CLIENT_MAX_BODY_CHARS` | `32768` | 文本响应返回前的默认截断字符上限 |
| `MCP_API_CLIENT_TEMP_DIR` | `<OS_TEMP>/mcp-server-api-client` | 下载文件、二进制与超长文本自动落盘目录 |

#### 远端 HTTP 传输与 Bearer 鉴权

需要跨进程或远程接入 MCP 服务时，建议结合 `--auth-token` 校验 `Authorization: Bearer <token>` 请求头（绑定非本机回环地址却未配置令牌时，服务端会在 `stderr` 输出安全提示但不阻断启动）：

<!-- Tested-By: tests/test_remote_auth.py#test_streamable_http_enforces_bearer_auth_when_token_configured -->
```bash
uv run mcp-server-api-client \
  --transport streamable-http \
  --host 0.0.0.0 \
  --port 8000 \
  --auth-token YOUR_API_TOKEN
```

### 6. 标准领域错误码 (`ErrorCode`)

除目标 API 返回的 HTTP `4xx`/`5xx` 作为正常响应回传外，网络、参数或连接池边界故障会统一转换为携带标准前缀的 MCP `ToolError`：

<!-- Tested-By: tests/test_errors.py#test_api_client_error_converts_to_prefixed_tool_error -->
| 错误码前缀 | 适用场景 |
| :--- | :--- |
| `[TIMEOUT]` | 连接、读取或流式等待超时 |
| `[CONNECTION_ERROR]` | DNS 解析失败、连接拒绝或对端网络不可达 |
| `[TLS_ERROR]` | `verify_ssl=True` 下证书校验失败或 TLS 握手异常 |
| `[INVALID_PARAMS]` | 请求体载荷互斥、本地文件不存在、非法 Hex/JSONPath 等参数异常 |
| `[NOT_FOUND]` | 访问不存在的 `ApiSession`、`SseSubscription` 或 `WsConnection` |
| `[POOL_LIMIT]` | 活跃 `SseSubscription` 或 `WsConnection` 数量达到连接池上限 |

### 7. 核心工具说明 (`http_request`)

在需要零配置验证后端接口、调试 GraphQL、识别图形验证码、抽取大 JSON 局部字段或进行文件上传下载时，可直接调用 `http_request` 工具（支持全 HTTP 方法、`params`、`headers`、`json`/`data`/`content`、`files`、`cookies`、`verify_ssl`、`follow_redirects`、`timeout_seconds`、`proxy`、`session`、`max_body_chars`、`extract_path` 与 `save_to_path`）：

- **轻量 JSONPath 提取 (`extract_path`)**：在大 JSON 截断前执行提取（支持 `$`、`.`/`[]`、`[*]`、`[a:b]` 与 `..`）；
- **光栅图多模态直出**：`<= 5MB` 光栅 `image/*` 且未传 `save_to_path` 时内联返回 `ImageContent`，超限自动落盘；`image/svg+xml` 返回文本源码；
- **文件上传与下载落盘**：`files` 支持单路径、列表及 `{path, filename, content_type}` 对象并可与 `data` 共存；二进制、`attachment` 与超长文本自动落盘至临时目录，`save_to_path` 支持目录文件名推断与覆写。

<!-- Tested-By: tests/test_http_request.py#test_http_request_executes_methods_payloads_and_unredacted_echo -->
```json
{
  "method": "POST",
  "url": "https://api.example.com/graphql",
  "headers": {
    "Authorization": "Bearer YOUR_API_TOKEN"
  },
  "json": {
    "query": "query { viewer { id } }",
    "variables": { "id": 42 }
  }
}
```

典型返回结构（遵循 ADR-0001 原样透明回显，HTTP `4xx`/`5xx` 亦按正常响应返回）：

<!-- Tested-By: tests/test_http_request.py#test_http_request_executes_methods_payloads_and_unredacted_echo -->
```json
{
  "status_code": 200,
  "reason_phrase": "OK",
  "final_url": "https://api.example.com/graphql",
  "redirect_count": 0,
  "elapsed_ms": 12.4,
  "request_headers": {
    "authorization": "Bearer YOUR_API_TOKEN",
    "content-type": "application/json"
  },
  "headers": {
    "content-type": "application/json"
  },
  "content_type": "application/json",
  "body_type": "json",
  "body": {
    "data": { "viewer": { "query": "query { viewer { id } }", "vars": { "id": 42 } } }
  },
  "truncated": false,
  "body_chars": 72,
  "body_bytes": 72,
  "saved_to_path": null
}
```

#### 文件上传、局部提取、图片识图与下载落盘示例

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_multipart_files_and_validation -->
```json
{
  "method": "POST",
  "url": "https://api.example.com/upload",
  "data": { "bizType": "avatar-upload" },
  "files": {
    "avatar": {
      "path": "/path/to/avatar.png",
      "filename": "custom-avatar.png",
      "content_type": "image/png"
    }
  }
}
```

文件上传响应结构示例：

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_multipart_files_and_validation -->
```json
{
  "status_code": 200,
  "body_type": "json",
  "body": {
    "fields": { "bizType": "avatar-upload" },
    "files": [
      {
        "field": "avatar",
        "filename": "custom-avatar.png",
        "content_type": "image/png"
      }
    ]
  }
}
```

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_extract_path_runs_before_truncation -->
```json
{
  "method": "GET",
  "url": "https://api.example.com/big-json",
  "extract_path": "$.data.items[0:2].name"
}
```

局部提取响应示例（在 `max_body_chars` 截断前完成抽取）：

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_extract_path_runs_before_truncation -->
```json
{
  "status_code": 200,
  "body_type": "json",
  "body": ["item-0", "item-1"],
  "truncated": false,
  "saved_to_path": null
}
```

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_handles_raster_image_svg_and_oversized_image -->
```json
{
  "method": "GET",
  "url": "https://api.example.com/captcha.png"
}
```

光栅图片内联响应示例（同时附带 `ImageContent` 内容块供多模态识图；若传入 `"save_to_path": "./downloads/"` 则直接落盘并返回 `saved_to_path`）：

<!-- Tested-By: tests/test_http_media_and_files.py#test_http_request_handles_raster_image_svg_and_oversized_image -->
```json
{
  "status_code": 200,
  "content_type": "image/png",
  "body_type": "image",
  "body": null,
  "saved_to_path": null
}
```

### 8. 命名内存会话 (`session_set` / `session_get` / `session_list` / `session_clear`)

在多步接口联调场景（如先登录获取 Token 或 `Set-Cookie`，再连续请求业务接口）中，可通过命名 `ApiSession` 集中维护 `base_url`、默认请求头、`CookieJar` 与网络默认值，并直接在 `http_request(session=...)` 中复用：

- `session_set`：创建或增量合并更新会话（支持设置 `base_url`、`headers`、`cookies`、`verify_ssl`、`follow_redirects`、`timeout_seconds` 与 `proxy`；其中 `headers` 按大小写无关合并及传 `null`/`None` 删除单键，`cookies` 按名称精确匹配更新及传 `null`/`None` 删除，`base_url`/`proxy` 传空字符串清空）；
- `session_get` / `session_list`：查看单个会话完整快照（含 `CookieJar` 条目）或列出全部活跃会话摘要（不存在时 `session_get` 抛出 `[NOT_FOUND]`）；
- `session_clear`：幂等清理指定会话（不存在时返回 `found=false`）；
- `http_request(session=...)`：相对路径保留 `base_url` 前缀拼接，完整绝对 URL 覆盖 `base_url`；请求级 `headers` / `cookies` 与网络参数单次优先覆盖（传 `proxy: ""` 可单次切回直连），临时 `cookies` 不污染会话 `CookieJar`。

<!-- Tested-By: tests/test_sessions.py#test_session_crud_incremental_merge_and_idempotent_clear -->
```json
{
  "session": "admin-api",
  "base_url": "https://api.example.com/v1",
  "headers": {
    "Authorization": "Bearer YOUR_API_TOKEN",
    "X-Tenant": "t1"
  },
  "verify_ssl": false
}
```

`session_set` / `session_get` 返回快照示例：

<!-- Tested-By: tests/test_sessions.py#test_session_crud_incremental_merge_and_idempotent_clear -->
```json
{
  "session": "admin-api",
  "base_url": "https://api.example.com/v1",
  "headers": {
    "Authorization": "Bearer YOUR_API_TOKEN",
    "X-Tenant": "t1"
  },
  "cookies": [],
  "verify_ssl": false,
  "follow_redirects": true,
  "timeout_seconds": 30.0,
  "proxy": null
}
```

`session_list` 返回示例：

<!-- Tested-By: tests/test_sessions.py#test_session_crud_incremental_merge_and_idempotent_clear -->
```json
{
  "sessions": [
    {
      "session": "admin-api",
      "base_url": "https://api.example.com/v1",
      "header_count": 2,
      "cookie_count": 0,
      "verify_ssl": false,
      "proxy": null
    }
  ],
  "total": 1
}
```

`session_clear`（`{"session": "admin-api"}`）返回示例：

<!-- Tested-By: tests/test_sessions.py#test_session_crud_incremental_merge_and_idempotent_clear -->
```json
{
  "session": "admin-api",
  "cleared": true,
  "found": true
}
```

### 9. SSE 流式响应 (`sse_request` / `sse_connect` / `sse_read_events` / `sse_list` / `sse_close`)

针对大模型流式对话（`POST` + JSON Body 返回 `text/event-stream`）及后台长连接事件推送场景，支持单次聚合读取与受管 `SseSubscription` 后台环形缓冲池：

- `sse_request`：支持全 HTTP 方法（默认 `GET`，常用 `POST`）、`params`、`headers`、`json`/`data`/`content`、`cookies`、`verify_ssl`、`follow_redirects`、`proxy` 与挂载 `ApiSession`（继承上下文并回写 `Set-Cookie`）；流式边界支持 `timeout_seconds`（未传时继承 `ApiSession` 或默认 `30.0`）、`idle_timeout_seconds`、`max_events`（默认 `100`）、`stop_on_done`（默认遇到 `[DONE]` 正常结束）与 `parse_json`；
- `sse_connect`：复用完整 HTTP 上下文与代理/TLS 配置，在 `timeout_seconds`（未传时继承 `ApiSession` 或默认 `30.0`）内同步等待 HTTP 响应头握手成功后方创建受管 `SseSubscription` 并分配 `sse_id`（遇 `4xx`/`5xx`、非 SSE 响应或握手超时直接失败不留僵尸订阅）；
- `sse_read_events`：默认推进内置游标并支持 `max_events`（默认 `50`）、`timeout_seconds` 软等待（默认 `2.0s`，传 `0` 非阻塞排空）、可选 `parse_json`（默认 `false` 自动解析 JSON 载荷）及可选 `since_seq` 回放历史事件（并报告溢出淘汰计数 `dropped_count`）；
- `sse_list` / `sse_close`：查看全部活跃订阅的缓冲与空闲时长快照，或按 `sse_id` 幂等关闭释放订阅（服务退出时自动全部清理）。

<!-- Tested-By: tests/test_sse.py#test_sse_request_parses_w3c_events_post_session_and_stop_conditions -->
```json
{
  "method": "POST",
  "url": "https://api.example.com/sse/chat",
  "session": "ai-chat",
  "json": { "prompt": "hello-sse" },
  "parse_json": true
}
```

`sse_request` 返回示例：

<!-- Tested-By: tests/test_sse.py#test_sse_request_parses_w3c_events_post_session_and_stop_conditions -->
```json
{
  "status_code": 200,
  "final_url": "https://api.example.com/sse/chat",
  "events": [
    {
      "seq": 1,
      "id": null,
      "event": "message",
      "data": { "prompt": "hello-sse" }
    }
  ],
  "done_received": true,
  "eof": true,
  "timed_out": false
}
```

`sse_connect`（`{"url": "https://api.example.com/sse/burst"}`）返回示例：

<!-- Tested-By: tests/test_sse.py#test_sse_subscription_pool_cursor_replay_soft_wait_and_bounds -->
```json
{
  "sse_id": "sse-a1b2c3d4e5f6",
  "status_code": 200,
  "final_url": "https://api.example.com/sse/burst",
  "session": null
}
```

`sse_read_events`（`{"sse_id": "sse-a1b2c3d4e5f6", "max_events": 10, "timeout_seconds": 0.0, "parse_json": true}`，环形容量 `3` 写入 `5` 条后消费）返回示例：

<!-- Tested-By: tests/test_sse.py#test_sse_subscription_pool_cursor_replay_soft_wait_and_bounds -->
```json
{
  "sse_id": "sse-a1b2c3d4e5f6",
  "events": [
    { "seq": 3, "id": "3", "event": "tick", "data": { "n": 3 } },
    { "seq": 4, "id": "4", "event": "tick", "data": { "n": 4 } },
    { "seq": 5, "id": "5", "event": "tick", "data": { "n": 5 } }
  ],
  "dropped_count": 2,
  "timed_out": false,
  "closed": false,
  "error": null
}
```

`sse_list` 返回示例：

<!-- Tested-By: tests/test_sse.py#test_sse_subscription_pool_cursor_replay_soft_wait_and_bounds -->
```json
{
  "subscriptions": [
    {
      "sse_id": "sse-a1b2c3d4e5f6",
      "url": "https://api.example.com/sse/burst",
      "method": "GET",
      "status_code": 200,
      "session": null,
      "closed": false,
      "error": null,
      "buffered_count": 3,
      "unread_count": 0,
      "dropped_count": 2,
      "last_seq": 5,
      "idle_seconds": 0.05
    }
  ],
  "total": 1
}
```

`sse_close`（`{"sse_id": "sse-a1b2c3d4e5f6"}`）返回示例：

<!-- Tested-By: tests/test_sse.py#test_sse_subscription_pool_cursor_replay_soft_wait_and_bounds -->
```json
{
  "sse_id": "sse-a1b2c3d4e5f6",
  "closed": true,
  "found": true
}
```

### 10. WebSocket 全双工 (`ws_send_once` / `ws_connect` / `ws_send` / `ws_recv` / `ws_list` / `ws_close`)

针对实时双工指令交互与持久化 WebSocket 通道调试场景，提供一次性短交互与受管 `WsConnection` 后台全双工连接池（统一支持 `params`、`headers`、`cookies`、`verify_ssl`、`proxy` 与挂载 `ApiSession` 的 `http(s)->ws(s)` 地址映射及匹配 `CookieJar` Cookies 注入）：

- `ws_send_once`：建立连接、按 `format`（`text`/`json`/`hex`）发送单条帧、等待最多 `max_messages`（默认 `1`）条响应或 `timeout_seconds`（未传时继承 `ApiSession` 或默认 `5.0`）后优雅断开；
- `ws_connect`：支持全量握手上下文与代理/TLS 配置，在 `timeout_seconds`（未传时继承 `ApiSession` 或默认 `30.0`）内等待 WebSocket 升级握手成功后分配 `ws_id` 并启动后台接收缓冲，`session_clear` 不中断已建立的长连接；
- `ws_send` / `ws_recv`：`ws_send` 支持 `text`/`json`/`hex` 发送并刷新活跃时间；`ws_recv` 支持 `max_messages`（默认 `50`）、软等待 `timeout_seconds`（默认 `5.0`，`0` 为非阻塞排空）与 `since_seq` 历史回溯，超时返回 `timed_out=True` 而不抛错，对端关闭准确返回 `closed`、`close_code` 与 `close_reason`；
- `ws_list` / `ws_close`：查看全双工连接与环形缓冲快照，或幂等关闭释放连接（服务端退出时自动回收全部长连接）。

<!-- Tested-By: tests/test_ws.py#test_ws_send_once_formats_session_mapping_and_errors -->
```json
{
  "url": "/ws/echo",
  "session": "ws-sess",
  "params": { "room": "alpha" },
  "format": "hex",
  "message": "de ad be ef",
  "max_messages": 2
}
```

`ws_send_once` 接收二进制帧自动编码为 Hex 的返回示例：

<!-- Tested-By: tests/test_ws.py#test_ws_send_once_formats_session_mapping_and_errors -->
```json
{
  "url": "ws://api.example.com/api/ws/echo?room=alpha",
  "status_code": 101,
  "sent_format": "hex",
  "sent_bytes": 4,
  "messages": [
    {
      "seq": 1,
      "frame_type": "text",
      "data": "{\"event\":\"handshake\"}",
      "byte_length": 21
    },
    {
      "seq": 2,
      "frame_type": "binary",
      "data": "deadbeef01",
      "byte_length": 5
    }
  ],
  "timed_out": false,
  "closed": false
}
```

长连接全双工建连（`ws_connect`）、发送（`ws_send`）、读取（`ws_recv` 捕获对端关闭码）、状态查询（`ws_list`）与幂等关闭（`ws_close`）典型入参及返回示例：

`ws_connect` 入参：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "url": "ws://api.example.com/ws/burst?count=5"
}
```

`ws_connect` 返回：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "ws_id": "ws-a1b2c3d4e5f6",
  "url": "ws://api.example.com/ws/burst?count=5",
  "status_code": 101,
  "session": null
}
```

`ws_send` 入参（向受管连接发送 JSON 帧）：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "ws_id": "ws-a1b2c3d4e5f6",
  "message": { "ping": 1 },
  "format": "json"
}
```

`ws_send` 返回：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "ws_id": "ws-a1b2c3d4e5f6",
  "sent_format": "json",
  "sent_bytes": 11
}
```

`ws_recv`（`{"ws_id": "ws-b2c3d4e5f6a7", "timeout_seconds": 0.5}`，捕获对端主动关闭状态码与原因）返回：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "ws_id": "ws-b2c3d4e5f6a7",
  "messages": [
    { "seq": 1, "frame_type": "text", "data": "bye-msg", "byte_length": 7 }
  ],
  "dropped_count": 0,
  "timed_out": false,
  "closed": true,
  "close_code": 4001,
  "close_reason": "session expired by peer",
  "error": null
}
```

`ws_list` 返回：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "connections": [
    {
      "ws_id": "ws-b2c3d4e5f6a7",
      "url": "ws://api.example.com/ws/close-info",
      "session": null,
      "closed": true,
      "close_code": 4001,
      "close_reason": "session expired by peer",
      "error": null,
      "buffered_count": 0,
      "unread_count": 0,
      "dropped_count": 0,
      "last_seq": 1,
      "idle_seconds": 0.08
    }
  ],
  "total": 1
}
```

`ws_close`（`{"ws_id": "ws-b2c3d4e5f6a7"}`）返回：

<!-- Tested-By: tests/test_ws.py#test_ws_connection_pool_duplex_cursor_close_info_and_limits -->
```json
{
  "ws_id": "ws-b2c3d4e5f6a7",
  "closed": true,
  "found": true
}
```

---

## 🚀 版本发版与发布

本项目基于 [`.github/workflows/release.yml`](./.github/workflows/release.yml) 实现自动化发版（前置质量门禁 + `uv build` 不可变产物 + GitHub Release + 按需分发 PyPI / GHCR 容器镜像）：

1. **GitHub 网页端一键发版**：前往仓库 **Actions -> Release -> Run workflow**，填入版本号（如 `v0.1.0`）即可；
2. **原生 Git 标签发版**：`git tag -a v0.1.0 -m "Release v0.1.0" && git push origin v0.1.0`；
3. **本地防呆发版脚本**：运行 `bash scripts/release.sh --dry-run` 预检，确认后运行 `bash scripts/release.sh`（自动执行 `uv version` 递增并校验主干同步状态）。

---

## 📂 仓库目录结构

```text
.
├── .githooks/
│   └── commit-msg                  # Git 原生 Conventional Commits 提交校验钩子
├── .github/
│   ├── ISSUE_TEMPLATE/             # Bug 反馈与特性建议 Issue 模板
│   ├── workflows/
│   │   ├── ci.yml                  # Python (uv) + Ruff + ShellCheck + pytest 分层门禁
│   │   └── release.yml             # 统合发版编排流水线 (Release / PyPI / GHCR)
│   ├── CODEOWNERS                  # PR 代码属主自动指派配置
│   ├── dependabot.yml              # GitHub Actions 与 Python 依赖月度自动巡检
│   └── PULL_REQUEST_TEMPLATE.md    # Pull Request 标准模板
├── docs/
│   └── adr/                        # 架构决策记录 (ADR-0001 / ADR-0002)
├── scripts/
│   ├── commit.sh                   # 规范化提交助手 (支持交互向导与 AI 非交互调用)
│   └── release.sh                  # 发版防呆脚本 (支持 Pre-flight 自检与版本号递增)
├── src/
│   └── mcp_server_api_client/      # MCP Server 核心源码包
│       ├── __init__.py             # 包版本元数据入口
│       ├── __main__.py             # CLI 启动入口 (stdio / sse / streamable-http)
│       ├── config.py               # CLI 与 MCP_API_CLIENT_* 配置解析及 stderr 日志
│       ├── doctor.py               # --check / --doctor 环境健康自检探针
│       ├── errors.py               # 领域异常体系与 ToolError 语义转换
│       ├── http_client.py          # 异步 HTTP/HTTPS 与 GraphQL 请求执行引擎
│       ├── jsonpath.py             # 零外部依赖轻量纯 Python JSONPath 提取器
│       ├── response_handler.py     # HTTP 响应分类、ImageContent 封装与文件落盘
│       ├── ring_buffer.py          # 定容单调序号环形缓冲与软等待游标读取
│       ├── schemas.py              # 请求参数校验、ApiSession 与流式响应 Pydantic v2 模型
│       ├── server.py               # MCPServer 实例构造、工具注册与 Bearer 鉴权中间件
│       ├── session_store.py        # 命名 ApiSession 内存注册表、CookieJar 与路径拼接
│       ├── sse_client.py           # W3C SSE 流解析器、单次采集与 SseSubscription 缓冲池
│       └── ws_client.py            # WebSocket 短交互与 WsConnection 全双工连接池
├── tests/
│   ├── test_config_and_doctor.py   # 配置优先级、非回环告警与 --check 探针测试
│   ├── test_errors.py              # 领域异常与 ToolError 转换测试
│   ├── test_http_media_and_files.py # JSONPath、ImageContent、落盘与 Multipart 上传测试
│   ├── test_http_request.py        # http_request 全链路、TLS、重定向与大文本落盘测试
│   ├── test_jsonpath.py            # 轻量 JSONPath 解析与异常语法单元测试
│   ├── test_remote_auth.py         # SSE / Streamable-HTTP Bearer 鉴权测试
│   ├── test_ring_buffer.py         # 有界环形缓冲序号、溢出计数与软等待单元测试
│   ├── test_sessions.py            # ApiSession 增量维护与 http_request 跨请求复用测试
│   ├── test_smoke.py               # 基础包结构、生命周期清理与 CLI 冒烟测试
│   ├── test_sse.py                 # sse_request 与 SseSubscription 缓冲池端到端测试
│   └── test_ws.py                  # ws_send_once 与 WsConnection 连接池端到端测试
├── .cliff.toml                     # git-cliff 自动化变更日志配置
├── .dockerignore                   # Docker 构建上下文忽略配置
├── .editorconfig                   # 跨编辑器编码与缩进规范
├── .gitattributes                  # 跨平台换行符归一化配置 (强制 LF)
├── .gitignore                      # Python / uv 与通用忽略配置
├── AGENTS.md                       # Python (MCP SDK v2) 工程规范与 AI Agent 协作准则
├── CODE_OF_CONDUCT.md              # 社区行为准则
├── CONTEXT.md                      # 领域统一语言词汇表 (ApiSession / SseSubscription / WsConnection)
├── CONTRIBUTING.md                 # 贡献指南与提交/发版规范
├── Dockerfile                      # 基于 python:3.11-slim 非 root 用户生产容器镜像
├── LICENSE                         # 开源许可证 (Apache-2.0)
├── pyproject.toml                  # Python 项目元数据、依赖与 Ruff/pytest 配置
├── README.md                       # 项目主文档
└── SECURITY.md                     # 安全策略与漏洞披露指南
```

---

## 🤝 参与贡献

欢迎提交 Issue 与 Pull Request！参与前请先阅读：
- [贡献指南 (CONTRIBUTING.md)](./CONTRIBUTING.md)
- [社区行为准则 (CODE_OF_CONDUCT.md)](./CODE_OF_CONDUCT.md)
- [安全策略 (SECURITY.md)](./SECURITY.md)

---

## 📄 开源许可证

本项目基于 [Apache License 2.0](./LICENSE) 协议开源。
