mcpField
C
Container-MCP

Container-MCP

远程服务
github.com/54rt1n云与基础设施2231 周前更新
代码仓库

关于 Container-MCP

Container-MCP 是基于 Podman 的 Ubuntu 24.04 容器化 MCP 服务,为大模型提供在沙箱中执行命令、Python 代码、文件操作和网页访问的工具。适合需要在隔离环境中安全运行 AI 生成操作的开发者。

主要功能

  1. 01命令与 Python 代码沙箱执行
  2. 02沙箱内文件读写、列表与补丁应用
  3. 03网页搜索、抓取与 Playwright 浏览
  4. 04知识库文档存储与语义搜索

适用场景

  1. 01在隔离容器中让 AI 运行命令或 Python 代码
  2. 02让 AI 在沙箱目录中读写和修改项目文件
  3. 03通过 MCP 工具抓取网页内容并存入知识库

MCP 相关

该项目是一个 MCP 服务,向 MCP 客户端暴露 system_run_command、fs_read、web_scrape、kb_create_document 等工具。工具分由 BashManager、PythonManager 等管理器提供。

配置

远程服务无需本地安装。选择你使用的客户端,复制配置或使用一键安装。

服务地址https://example.com/page
一键复制安装命令
Claude CodeTerminal
Cursor.cursor/mcp.json
VS Code.vscode/mcp.json
Claude Desktopclaude_desktop_config.json
Windsurf~/.codeium/windsurf/mcp_config.json

命令在终端中运行;JSON 粘贴到对应客户端的 MCP 配置后重启。需要授权的服务会在首次连接时提示登录。

工具

详细介绍

Container-MCP

License: Apache 2.0

一种安全的、基于容器的模型上下文协议(MCP)实现,可代表大模型执行工具。

概述

Container-MCP 提供了一个沙箱环境,可安全地执行代码、运行命令、访问文件以及执行大模型请求的 Web 操作。它实现了 MCP 协议,将这些功能作为工具公开,供 AI 系统以安全的方式发现和调用。

该架构采用特定领域的管理器模式,并通过多层安全机制确保工具在隔离环境中按适当限制执行,从而保护宿主系统免受潜在有害操作的影响。

主要功能

  • 多层安全机制

    • 使用 Podman/Docker 进行容器隔离
    • 使用 AppArmor 配置文件限制访问
    • 使用 Firejail 沙箱提供额外隔离
    • 资源限制(CPU、内存、执行时间)
    • 防止路径遍历
    • 限制允许的扩展名
  • MCP 协议实现

    • 标准化的工具发现和执行
    • 资源管理
    • 支持异步执行
  • 特定领域管理器

    • BashManager:安全执行命令
    • PythonManager:在沙箱中执行 Python 代码
    • FileManager:安全执行文件操作
    • WebManager:安全浏览网页和抓取内容
    • KnowledgeBaseManager:结构化文档存储与语义搜索
    • ListManager:有序管理列表和集合
    • MarketManager:通过 Yahoo Finance 获取股票和加密货币数据
    • RssManager:获取 RSS 和 Atom 订阅源
  • 可配置环境

    • 通过环境变量进行广泛配置
    • 支持自定义环境
    • 开发和生产模式

可用工具

系统操作
system_run_command

在安全的沙箱环境中执行 bash 命令。

  • 参数:
    • command(string,必填):要执行的 bash 命令
    • working_dir(string,可选):工作目录(在沙箱中忽略)
  • 返回值:
    • stdout(string):命令的标准输出
    • stderr(string):命令的标准错误输出
    • exit_code(integer):命令的退出码
    • success(boolean):命令是否成功完成
{
  "stdout": "file1.txt\nfile2.txt\n",
  "stderr": "",
  "exit_code": 0,
  "success": true
}
system_run_python

在安全的沙箱环境中执行 Python 代码。

  • 参数:
    • code(string,必填):要执行的 Python 代码
    • working_dir(string,可选):工作目录(在沙箱中忽略)
  • 返回值:
    • output(string):代码的打印输出
    • error(string):代码的错误输出
    • result(any):可选返回值(代码设置 _ 变量后可用)
    • success(boolean):代码是否成功执行
{
  "output": "Hello, world!\n",
  "error": "",
  "result": 42,
  "success": true
}
system_env_var

获取环境变量值。

  • 参数:
    • var_name(string,可选):要获取的特定变量
  • 返回值:
    • variables(object):环境变量字典
    • requested_var(string):所请求变量的值(如果提供了 var_name)
{
  "variables": {
    "MCP_PORT": "8000",
    "SANDBOX_ROOT": "/app/sandbox"
  },
  "requested_var": "8000"
}
health_check

获取服务健康状态和系统信息。

  • 参数:无
  • 返回值:
    • status(string):服务健康状态
    • timestamp(string):当前 ISO 时间戳
    • server(object):服务详情(name、host、port、platform、python_version)
    • system(object):系统指标(cpu_percent、memory_percent、disk_percent)
    • managers(object):各管理器的状态(启用/禁用)
{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "server": {
    "name": "Container-MCP",
    "host": "127.0.0.1",
    "port": 9001,
    "platform": "linux",
    "python_version": "3.12.0"
  },
  "system": {
    "cpu_percent": 12.5,
    "memory_percent": 45.2,
    "disk_percent": 67.8
  },
  "managers": {
    "bash": "enabled",
    "python": "enabled",
    "file": "enabled",
    "web": "enabled",
    "kb": "enabled",
    "list": "enabled",
    "market": "enabled",
    "rss": "enabled"
  }
}
文件操作
fs_read

安全地读取文件内容。

  • 参数:
    • path(string,必填):文件路径(相对于沙箱根目录)
    • encoding(string,可选):文件编码(默认值:"utf-8")
  • 返回值:
    • content(string):文件内容
    • size(integer):文件大小,单位为字节
    • modified(float):上次修改时间戳
    • success(boolean):读取是否成功
{
  "content": "This is the content of the file.",
  "size": 31,
  "modified": 1673452800.0,
  "success": true
}
fs_write

安全地将内容写入文件。

  • 参数:
    • path(string,必填):文件路径(相对于沙箱根目录)
    • content(string,必填):要写入的内容
    • encoding(string,可选):文件编码(默认值:"utf-8")
  • 返回值:
    • success(boolean):写入是否成功
    • path(string):写入文件的路径
{
  "success": true,
  "path": "data/myfile.txt"
}
fs_list

安全地列出目录内容。

  • 参数:
    • path(string,可选):目录路径(默认值:"/")
    • pattern(string,可选):用于筛选文件的 Glob 模式
    • recursive(boolean,可选):是否递归列出(默认值:true)
  • 返回值:
    • entries(array):包含元数据的目录条目列表
    • path(string):列出的目录路径
    • success(boolean):列出操作是否成功
{
  "entries": [
    {
      "name": "file1.txt",
      "path": "file1.txt",
      "is_directory": false,
      "size": 1024,
      "modified": 1673452800.0
    },
    {
      "name": "data",
      "path": "data",
      "is_directory": true,
      "size": null,
      "modified": 1673452500.0
    }
  ],
  "path": "/",
  "success": true
}
fs_delete

安全地删除文件。

  • 参数:
    • path(string,必填):要删除的文件路径
  • 返回值:
    • success(boolean):删除是否成功
    • path(string):已删除文件的路径
{
  "success": true,
  "path": "temp/old_file.txt"
}
fs_move

安全地移动或重命名文件。

  • 参数:
    • source_path(string,必填):源文件路径
    • destination_path(string,必填):目标文件路径
  • 返回值:
    • success(boolean):移动是否成功
    • source_path(string):原文件路径
    • destination_path(string):新文件路径
{
  "success": true,
  "source_path": "data/old_name.txt",
  "destination_path": "data/new_name.txt"
}
fs_apply_diff

将统一 diff 补丁应用到沙箱文件系统中的文件。

  • 参数:
    • path(string,必填):要打补丁的文件路径(相对于沙箱根目录)
    • diff(string,必填):要应用的统一 diff 内容
  • 返回值:
    • success(boolean):补丁是否成功应用
    • path(string):已打补丁文件的路径
    • lines_applied(integer):更改的行数
    • new_size(integer):新文件大小,单位为字节
    • error(string):补丁应用失败时的错误消息
{
  "success": true,
  "path": "src/main.py",
  "lines_applied": 5,
  "new_size": 1248,
  "error": null
}
Web 操作
web_search

使用搜索引擎在 Web 上查找信息。

  • 参数:
    • query(string,必填):要搜索的查询内容
  • 返回值:
    • results(array):搜索结果列表
    • query(string):原始查询内容
{
  "results": [
    {
      "title": "Search Result Title",
      "url": "https://example.com/page1",
      "snippet": "Text snippet from the search result..."
    }
  ],
  "query": "example search query"
}
web_scrape

抓取指定 URL 并返回内容。

  • 参数:
    • url(string,必填):要抓取的 URL
    • selector(string,可选):用于定位特定内容的 CSS 选择器
    • output_format(string,可选):使用 "markdown" 返回 Markdown(保留链接)。默认使用纯文本。
  • 返回值:
    • content(string):抓取的内容
    • url(string):已抓取的 URL
    • title(string):页面标题
    • success(boolean):抓取是否成功
    • error(string):抓取失败时的错误消息
{
  "content": "This is the content of the web page...",
  "url": "https://example.com/page",
  "title": "Example Page",
  "success": true,
  "error": null
}

Markdown 输出示例:

{
  "content": "This is a [link](https://example.com) in Markdown...",
  "url": "https://example.com/page",
  "title": "Example Page",
  "success": true,
  "error": null
}
web_browse

使用 Playwright 交互式浏览网站。

注意:web_browse 需要 Playwright 浏览器二进制文件。在容器外,请使用 python -m playwright install chromium(或 playwright install)进行安装。

  • 参数:
    • url(string,必填):浏览会话的起始 URL
  • 返回值:
    • content(string):页面 HTML 内容
    • url(string):重定向后的最终 URL
    • title(string):页面标题
    • success(boolean):浏览是否成功
    • error(string):浏览失败时的错误消息
{
  "content": "<!DOCTYPE html><html>...</html>",
  "url": "https://example.com/after_redirect",
  "title": "Example Page",
  "success": true,
  "error": null
}
知识库操作

知识库系统提供结构化文档存储、语义搜索功能、RDF 风格的关系以及元数据管理。文档按分层命名空间结构组织,并支持偏好(任意 RDF 三元组)和引用(文档之间的链接)。

文档 URI 格式

知识库文档使用结构化 URI 格式:kb://namespace/collection[/subcollection]*/name

  • namespace:顶层组织单元(例如,“projects”“research”)
  • collection:命名空间中的主要类别(例如,“documentation”“notes”)
  • subcollection:可选的嵌套类别(例如,“api”“tutorials”)
  • name:文档标识符(例如,“getting-started”“user-guide”)

示例:

  • kb://projects/docs/api-reference
  • kb://research/papers/machine-learning/transformers
  • kb://personal/notes/meeting-2024-01-15
kb_create_document

在知识库中创建新文档,并可选择添加元数据和内容。

  • 参数:
    • uri(string,必填):格式为 "kb://namespace/collection[/subcollection]*/name" 的文档 URI
    • metadata(object,可选):文档元数据(默认值:{})
    • content(string,可选):文档内容(支持单步创建和写入)
  • 返回值:
    • 包含创建详情的完整文档索引对象
  • 备注:提供 content 参数即可一步创建包含内容的文档;也可以分两步操作,先创建文档,再使用 kb_write_content 添加内容。
{
  "namespace": "projects",
  "collection": "docs",
  "name": "api-reference",
  "type": "document",
  "subtype": "text",
  "created_at": "2024-01-15T10:30:00.000Z",
  "updated_at": "2024-01-15T10:30:00.000Z",
  "content_type": "text/plain",
  "chunked": false,
  "fragments": {},
  "preferences": [],
  "references": [],
  "referenced_by": [],
  "indices": [],
  "metadata": {"author": "John Doe", "version": "1.0"}
}
kb_write_content

将内容写入知识库中的现有文档。

  • 参数:
    • uri(string,必填):文档 URI
    • content(string,必填):文档内容
    • force(boolean,可选):是否覆盖现有内容(默认值:false)
  • 返回值:
    • 完整的更新后文档索引对象
  • 备注:必须先使用 kb_create_document 创建文档。
{
  "namespace": "projects",
  "collection": "docs", 
  "name": "api-reference",
  "type": "document",
  "subtype": "text",
  "created_at": "2024-01-15T10:30:00.000Z",
  "updated_at": "2024-01-15T10:35:00.000Z",
  "content_type": "text/plain",
  "chunked": false,
  "fragments": {},
  "preferences": [],
  "references": [],
  "referenced_by": [],
  "indices": [],
  "metadata": {"author": "John Doe", "version": "1.0"}
}
kb_read

从知识库读取文档数据。不提供 uri 时,会列出所有文档(无需单独的列表操作)。

  • 参数:
    • uri(string,可选):文档 URI。省略时,将列出所有文档。
    • recursive(boolean,可选):是否递归列出(默认值:true)
    • include_content(boolean,可选):是否包含文档内容(默认值:false)
    • include_index(boolean,可选):是否包含文档元数据(默认值:false)
  • 返回值:
    • 根据请求的组成部分返回文档数据。支持三种模式:
      • 列表模式:省略 uri 时,返回文档 URI 列表
      • 批量读取模式:uri 为部分路径(命名空间或集合)时,返回多个文档
      • 读取模式:uri 为完整文档路径时,返回单个文档

读取单个文档:

{
  "status": "success",
  "uri": "kb://projects/docs/api-reference",
  "content": "This is the API reference content...",
  "index": {
    "namespace": "projects",
    "collection": "docs",
    "name": "api-reference",
    "created_at": "2024-01-15T10:30:00Z",
    "metadata": {"author": "John Doe"}
  }
}

列出所有文档(不提供 uri):

{
  "mode": "list",
  "documents": [
    "kb://projects/docs/api-reference",
    "kb://projects/docs/user-guide",
    "kb://research/papers/transformers"
  ],
  "count": 3
}
kb_update_triples

管理文档的 RDF 三元组(偏好、引用和元数据)。此工具还可通过 triple_type="metadata" 更新元数据,无需单独的元数据更新操作。

  • 参数:
    • action(string,必填):要执行的操作("add" 或 "remove")
    • triple_type(string,必填):三元组类型("preference"、"reference" 或 "metadata")
    • uri(string,必填):源文档 URI
    • predicate(string,必填):三元组的谓词
    • object(string,可选):三元组的对象(用于偏好和元数据)
    • ref_uri(string,可选):被引用文档的 URI(仅用于引用)
  • 返回值:
    • 操作状态和更新后的计数

添加偏好(任意 RDF 三元组):

{
  "status": "updated",
  "preference_count": 3,
  "action": "add",
  "triple_type": "preference"
}

添加引用(指向另一文档的链接):

{
  "status": "success",
  "message": "Reference added",
  "added": true,
  "action": "add",
  "triple_type": "reference"
}

更新元数据:

{
  "status": "updated",
  "action": "add",
  "triple_type": "metadata"
}

移除引用:

{
  "status": "updated",
  "reference_count": 2,
  "action": "remove",
  "triple_type": "reference"
}
kb_search

使用文本查询和/或图谱扩展搜索知识库。

  • 参数:
    • query(string,可选):用于语义搜索和重新排序的文本查询
    • seed_uris(array,可选):用于图谱扩展的起始完整 URI(kb://namespace/collection/name)
    • root_uri(string,可选):用于限定搜索范围的部分 URI(kb://namespace 或 kb://namespace/collection)
    • expand_hops(integer,可选):扩展的关系跳数(默认值:0)
    • filter_uris(array,可选):从结果中排除的 URI
    • relation_predicates(array,可选):图遍历时要沿用的谓词(默认值:["references"])
    • top_k_sparse(integer,可选):要检索的稀疏搜索结果数量(默认值:50)
    • top_k_rerank(integer,可选):重新排序后的最终结果数量(默认值:10)
    • include_content(boolean,可选):是否包含文档内容(默认值:false)
    • include_index(boolean,可选):是否包含文档元数据(默认值:false)
    • use_reranker(boolean,可选):是否使用语义重新排序(默认值:true)
  • 返回:
    • 排序后的搜索结果列表
{
  "results": [
    {
      "urn": "kb://projects/docs/api-reference",
      "sparse_score": 1.95,
      "content": "API reference content...",
      "index": {
        "namespace": "projects",
        "collection": "docs",
        "name": "api-reference",
        "type": "document",
        "subtype": "text",
        "created_at": "2025-07-02T23:13:17.362283Z",
        "updated_at": "2025-07-02T23:18:23.396660Z",
        "content_type": "text/plain",
        "chunked": false,
        "fragments": {},
        "preferences": [],
        "references": [
          [
            "references",
            "kb://project/docs/api-dto"
          ]
        ],
        "referenced_by": [],
        "indices": [],
        "metadata": {
          "purpose": "testing_collection_organization",
          "created_for": "kb_exercise",
          "type": "test_document",
          "created_date": "2025-07-02",
          "topic": "search_performance",
          "related_to": "rebuild_test"
        }
      },
      "rerank_score": 0.84,
    }
  ],
  "count": 1
}
kb_manage

管理知识库操作,例如移动文档和重建搜索索引。

  • 参数:
    • action(string,必填):要执行的管理操作
      • "move_document":移动文档
      • "delete":归档文档
      • "rebuild_search_index":重建搜索索引
    • options(object,必填):特定于操作的选项
      • 对于 "move_document":{"uri": "...", "new_uri": "..."}
      • 对于 "delete":{"uri": "..."}
      • 对于 "rebuild_search_index":{"rebuild_all": true}(可选)
  • 返回:
    • 操作状态和结果

移动文档:

{
  "action": "move_document",
  "status": "success",
  "old_path": "projects/docs/old-name",
  "new_path": "projects/docs/new-name",
  "result": {
    "namespace": "projects",
    "collection": "docs",
    "name": "new-name",
    "type": "document",
    "subtype": "text",
    "created_at": "2024-01-15T10:30:00.000Z",
    "updated_at": "2024-01-15T10:50:00.000Z",
    "content_type": "text/plain",
    "chunked": false,
    "fragments": {},
    "preferences": [],
    "references": [],
    "referenced_by": [],
    "indices": [],
    "metadata": {}
  }
}

归档文档:

{
  "action": "delete",
  "status": "success", 
  "path": "projects/docs/obsolete",
  "result": {
    "status": "archived",
    "message": "Document archived: kb://projects/docs/obsolete",
    "original_path": "projects/docs/obsolete",
    "archive_path": "archive/projects/docs/obsolete",
    "archive_urn": "kb://archive/projects/docs/obsolete"
  }
}
列表操作

列表系统基于 org-mode,提供任务、笔记、购物和通用集合的列表管理功能。列表支持多种项目状态,也可以添加标签以便整理。

项目状态

列表中的项目可以具有以下状态:TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY

列表类型

列表类型可以是:todo、shopping、notes、checklist、project、reading、ideas

list_create

创建用于管理任务、笔记、购物内容或任意集合的新列表。

  • 参数:
    • name(string,必填):列表的内部名称(用作文件名)
    • title(string,可选):列表的显示标题
    • list_type(string,可选):列表类型(默认值:"todo")
    • description(string,可选):可选描述
    • tags(array,可选):用于整理的标签
    • properties(object,可选):用户自定义属性
  • 返回:
    • success(boolean):是否创建成功
    • name(string):列表名称
    • metadata(object):标题、类型、创建时间戳和属性
    • path(string):文件路径
{
  "success": true,
  "name": "grocery-list",
  "metadata": {
    "title": "Weekly Groceries",
    "type": "shopping",
    "created": "2024-01-15T10:30:00.000Z",
    "properties": {}
  },
  "path": "/app/lists/grocery-list.org"
}
list_get

通过灵活的筛选选项检索和浏览列表。

  • 参数:
    • name(string,可选):要检索的特定列表名称。省略时,将列出所有可用列表。
    • include_items(boolean,可选):是否在响应中包含项目(默认值:true)
    • summary_only(boolean,可选):仅返回摘要统计信息,不包含项目(默认值:false)
    • status_filter(string,可选):按状态筛选项目(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
    • tag_filter(array,可选):按标签筛选项目(项目必须包含所有指定标签)
  • 返回:
    • 省略 name 时:lists(摘要数组)、count
    • 提供 name 时:name、metadata、items、statistics

列出所有列表:

{
  "success": true,
  "lists": [
    {"name": "grocery-list", "title": "Weekly Groceries", "type": "shopping"},
    {"name": "project-tasks", "title": "Q1 Tasks", "type": "todo"}
  ],
  "count": 2
}

获取特定列表:

{
  "success": true,
  "name": "project-tasks",
  "metadata": {"title": "Q1 Tasks", "type": "todo"},
  "items": [
    {
      "text": "Complete API integration",
      "status": "TODO",
      "index": 0,
      "tags": ["backend"],
      "created": "2024-01-15T10:30:00.000Z",
      "completed": null,
      "properties": {}
    }
  ],
  "statistics": {
    "total_items": 5,
    "status_counts": {"TODO": 3, "DONE": 2},
    "completion_percentage": 40.0
  }
}
list_modify

通过添加、更新或移除列表项来修改列表项。

  • 参数:
    • list_name(string,必填):列表名称
    • action(string,必填):要执行的操作(“add”、“update”或“remove”)
    • item_text(string,可选):列表项的文本(“add”时必填,“update”时可选)
    • item_index(integer,可选):列表项的索引(“update”和“remove”时必填)
    • status(string,可选):列表项状态(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
    • tags(array,可选):列表项的标签
    • properties(object,可选):自定义属性
  • 返回值:
    • success(boolean):操作是否成功
    • action(string):执行的操作
    • item(object):受影响列表项的详细信息

添加列表项:

{
  "success": true,
  "action": "add",
  "item": {
    "text": "Buy milk",
    "status": "TODO",
    "index": 3,
    "tags": ["dairy"]
  },
  "total_items": 4
}

更新列表项:

{
  "success": true,
  "action": "update",
  "item_index": 0,
  "item": {"text": "Buy milk", "status": "DONE"},
  "old_item": {"text": "Buy milk", "status": "TODO"}
}

移除列表项:

{
  "success": true,
  "action": "remove",
  "removed_item": {"text": "Buy milk", "status": "DONE", "index": 0},
  "remaining_items": 3
}
list_update

更新列表属性和元数据。属性采用合并语义——仅更新提供的键,保留现有键。

  • 参数:
    • name(string,必填):列表名称
    • title(string,可选):新标题
    • list_type(string,可选):新列表类型
    • description(string,可选):新描述
    • tags(array,可选):新标签(替换现有标签)
    • author(string,可选):新作者
    • properties(object,可选):自定义属性(与现有属性合并)
  • 返回值:
    • success(boolean):更新是否成功
    • name(string):列表名称
    • metadata(object):更新后的元数据
{
  "success": true,
  "name": "project-tasks",
  "metadata": {
    "title": "Q1 Tasks - Updated",
    "type": "project",
    "tags": ["work", "q1"],
    "description": "Updated project task list"
  }
}
list_delete

永久删除整个列表及其所有列表项。为安全起见,列表文件会被归档,但此后无法通过常规操作访问该列表。

  • 参数:
    • name(string,必填):要删除的列表名称
  • 返回值:
    • success(boolean):删除是否成功
    • name(string):已删除的列表名称
    • items_count(integer):列表中原有的列表项数量
    • archived_to(string):归档文件路径
{
  "success": true,
  "name": "old-grocery-list",
  "items_count": 12,
  "archived_to": "/app/lists/.archive/old-grocery-list.org"
}
list_search

按文本或标签搜索多个列表中的列表项。

  • 参数:
    • query(string,必填):搜索查询字符串
    • list_names(array,可选):要搜索的特定列表(省略时搜索所有列表)
    • search_in(array,可选):搜索范围:“text”、“tags”或两者(默认值:["text"])
    • case_sensitive(boolean,可选):搜索是否区分大小写(默认值:false)
  • 返回值:
    • matches(array):匹配的列表项及其列表上下文
    • total_matches(integer):匹配总数
    • lists_searched(integer):已搜索的列表数量
    • search_options(object):已应用的搜索参数
{
  "success": true,
  "query": "milk",
  "matches": [
    {
      "list_name": "grocery-list",
      "list_title": "Weekly Groceries",
      "item_index": 2,
      "item_text": "Buy milk",
      "item_status": "TODO",
      "item_tags": ["dairy"],
      "match_type": "text"
    }
  ],
  "total_matches": 1,
  "lists_searched": 3,
  "search_options": {
    "search_in": ["text"],
    "case_sensitive": false
  }
}
市场操作

市场系统使用 Yahoo Finance 查询股票和加密货币的金融数据。

market_query

查询股票或加密货币价格,并提供基本面、新闻和趋势分析。

  • 参数:
    • symbol(字符串,必填):股票/加密货币代码(例如,“AAPL”、“BTC-USD”、“TSLA”)
    • period(字符串,可选):用于趋势指标的历史周期(默认值:“1y”)
    • interval(字符串,可选):历史数据间隔(默认值:“1d”)
    • news_count(整数,可选):要返回的近期新闻条数(默认值:5)
  • 返回值:
    • symbol(字符串):查询的代码
    • name(字符串):公司/资产名称
    • price(浮点数):当前价格
    • change(浮点数):价格变动
    • change_percent(浮点数):变动百分比
    • volume(整数):交易量
    • market_cap(整数):市值
    • currency(字符串):货币代码
    • timestamp(字符串):ISO 格式的时间戳
    • fundamentals(对象):收益、PE 比率、股息、利润率
    • news(数组):近期新闻条目
    • trend(对象):移动平均线、RSI、波动率、历史回报
    • success(布尔值):查询是否成功
    • error(字符串):查询失败时的错误消息
{
  "symbol": "AAPL",
  "name": "Apple Inc.",
  "price": 185.92,
  "change": 2.35,
  "change_percent": 1.28,
  "volume": 54321000,
  "market_cap": 2890000000000,
  "currency": "USD",
  "timestamp": "2024-01-15T16:00:00Z",
  "fundamentals": {
    "trailing_pe": 29.5,
    "forward_pe": 27.8,
    "dividend_yield": 0.0054,
    "profit_margin": 0.256,
    "earnings_quarterly_growth": 0.13
  },
  "news": [
    {
      "title": "Apple Reports Strong Q4 Earnings",
      "link": "https://example.com/article",
      "publisher": "Reuters",
      "published": "2024-01-15T12:00:00Z",
      "type": "STORY"
    }
  ],
  "trend": {
    "as_of": "2024-01-15T16:00:00Z",
    "close": 185.92,
    "return_1w": 0.023,
    "return_1m": 0.045,
    "return_3m": 0.12,
    "ma20": 183.50,
    "ma50": 180.25,
    "ma200": 175.80,
    "rsi14": 58.3,
    "volatility_20d": 0.18,
    "range_52w_low": 164.08,
    "range_52w_high": 199.62,
    "data_points": 252
  },
  "success": true,
  "error": null
}
RSS 操作

RSS 系统会获取并解析 RSS 和 Atom 订阅源。

rss_fetch

获取并解析 RSS 或 Atom 订阅源,并返回结构化条目。

  • 参数:
    • url(字符串,必填):RSS 订阅源 URL
    • limit(整数,可选):要返回的最大条目数(默认值:10)
  • 返回值:
    • feed_title(字符串):订阅源标题
    • feed_link(字符串):订阅源网站链接
    • items(数组):订阅源条目,每个条目包含:
      • title(字符串):条目标题
      • link(字符串):条目 URL
      • published(字符串):发布日期
      • summary(字符串):条目摘要/描述
    • item_count(整数):返回的条目数
    • success(布尔值):获取是否成功
    • error(字符串):获取失败时的错误消息
{
  "feed_title": "Hacker News",
  "feed_link": "https://news.ycombinator.com",
  "items": [
    {
      "title": "Show HN: A new open-source project",
      "link": "https://example.com/project",
      "published": "2024-01-15T14:30:00Z",
      "summary": "An innovative approach to solving..."
    }
  ],
  "item_count": 10,
  "success": true,
  "error": null
}

执行环境

Container-MCP 为不同类型的操作提供隔离的执行环境,每种环境都有自己的安全措施和资源限制。

容器环境

主要的 Container-MCP 服务运行在容器中(使用 Podman 或 Docker),提供第一层隔离:

  • 基础镜像:Ubuntu 24.04
  • 用户:非 root 的 ubuntu 用户
  • Python:3.12
  • 网络:仅限绑定到 localhost
  • 文件系统:为配置、数据和日志挂载卷
  • 安全性:AppArmor、Seccomp 和能力限制
Bash 执行环境

Bash 执行环境配置了多层隔离机制:

  • 允许的命令:限制为在 BASH_ALLOWED_COMMANDS 中配置的安全命令
  • Firejail 沙箱:隔离进程并限制文件系统访问
  • AppArmor 配置文件:精细控制访问权限
  • 资源限制:
    • 执行超时(默认值:30s,最长:120s)
    • 仅允许访问沙箱内的目录
  • 网络:无网络访问权限
  • 文件系统:只读访问数据,可读写访问沙箱

允许的命令示例:

ls, cat, grep, find, echo, pwd, mkdir, touch
Python 执行环境

Python 执行环境专为安全执行代码而设计:

  • Python 版本:3.12
  • 内存限制:可配置的内存上限(默认值:256MB)
  • 执行超时:可配置的时间限制(默认值:30s,最长:120s)
  • AppArmor 配置文件:限制对系统资源的访问
  • Firejail 沙箱:隔离进程
  • 能力:禁用所有能力
  • 网络:无网络访问权限
  • 可用库:仅限标准库
  • 输出捕获:重定向并清理 stdout/stderr
  • 资源控制:强制实施 CPU 和内存限制
文件系统环境

文件系统环境控制对沙盒内文件的访问:

  • 基础目录:所有操作均限制在沙盒根目录内
  • 路径验证:规范化所有路径并检查路径遍历尝试
  • 大小限制:强制执行最大文件大小限制(默认:10MB)
  • 扩展名控制:仅允许指定扩展名(默认:txt、md、csv、json、py)
  • 权限控制:强制执行适当的读写权限
  • 隔离:无法访问主机文件系统
Web 环境

Web 环境提供对外部资源的受控访问:

  • 域名控制:可选的允许域名白名单
  • 超时控制:可配置操作超时时间
  • 浏览器控制:通过 Playwright 使用无头浏览器进行完整渲染
  • 抓取控制:通过 requests/BeautifulSoup 进行简单抓取
  • 内容净化:解析并净化所有内容
  • 网络隔离:通过容器使用独立的网络命名空间
知识库环境

知识库环境提供结构化文档存储和语义搜索:

  • 分层组织:文档按 namespace/collection/name 结构组织
  • 元数据管理:支持丰富的元数据和 RDF 风格三元组
  • 语义搜索:使用稀疏索引和语义重排序进行全文搜索
  • 图关系:通过关系遍历文档引用
  • 路径验证:严格验证和规范化路径
  • 搜索索引:分别建立稀疏索引和图索引,以优化性能
  • 超时控制:可配置操作超时时间(默认:30s,最长:120s)
  • 隔离:知识库操作限制在配置的存储路径内
列表环境

列表环境提供有序的集合管理:

  • Org-mode 格式:列表以 org-mode 文件形式存储,便于移植
  • 状态跟踪:条目支持多种状态(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
  • 标签:条目和列表均支持标签,便于灵活组织
  • 归档:删除的列表会归档以确保安全
  • 搜索:按文本和标签跨列表搜索
  • 隔离:列表操作限制在配置的存储路径内
市场环境

市场环境提供对金融数据的受控访问:

  • 数据来源:Yahoo Finance 的股票和加密货币数据
  • 超时控制:可配置超时时间(默认:30s,最长:60s)
  • 数据类型:价格报价、基本面数据、新闻和趋势分析
RSS 环境

RSS 环境提供 Feed 获取功能:

  • Feed 类型:支持 RSS 和 Atom Feed
  • 超时控制:可配置超时时间(默认:15s,最长:30s)
  • 用户代理:可配置用户代理字符串
  • 条目限制:可配置每次获取的最大条目数

架构

项目采用模块化架构:

container-mcp/
├── cmcp/                     # Main application code
│   ├── managers/             # Domain-specific managers
│   │   ├── bash_manager.py   # Secure bash execution
│   │   ├── file_manager.py   # Secure file operations
│   │   ├── knowledge_base_manager.py # Knowledge base operations
│   │   ├── list_manager.py   # List/collection operations
│   │   ├── market_manager.py # Market data operations
│   │   ├── python_manager.py # Secure python execution
│   │   ├── rss_manager.py    # RSS feed operations
│   │   └── web_manager.py    # Secure web operations
│   ├── kb/                   # Knowledge base components
│   │   ├── document_store.py # Document storage and retrieval
│   │   ├── models.py         # Data models and schemas
│   │   ├── path.py           # Path parsing and validation
│   │   └── search.py         # Search indices and ranking
│   ├── tools/                # MCP tool implementations
│   │   ├── file.py           # File operation tools
│   │   ├── kb.py             # Knowledge base tools
│   │   ├── list.py           # List operation tools
│   │   ├── market.py         # Market data tools
│   │   ├── rss.py            # RSS feed tools
│   │   ├── system.py         # System operation tools
│   │   └── web.py            # Web operation tools
│   ├── utils/                # Utility functions
│   │   ├── diff.py           # Diff/patch utilities
│   │   ├── io.py             # I/O helpers
│   │   └── logging.py        # Logging utilities
│   ├── __init__.py
│   ├── config.py             # Configuration system
│   └── main.py               # MCP server setup
├── apparmor/                 # AppArmor profiles
│   ├── mcp-bash              # Bash execution profile
│   └── mcp-python            # Python execution profile
├── bin/                      # Build/run scripts
│   ├── 00-all-in-one.sh      # Complete setup script
│   ├── 01-init.sh            # Project initialization
│   ├── 02-build-container.sh # Container build script
│   ├── 03-setup-environment.sh # Environment setup
│   ├── 04-run-container.sh   # Container run script
│   ├── 05-check-container.sh # Container health check
│   ├── 06-run-tests.sh       # Test execution
│   ├── 07-attach-container.sh # Container shell access
│   ├── 08-testnetwork.sh     # Network testing
│   ├── 09-view-logs.sh       # Log viewing
│   ├── zy-shutdown.sh        # Container shutdown
│   └── zz-teardown.sh        # Complete teardown
├── tests/                    # Test suites
│   ├── integration/          # Integration tests
│   ├── unit/                 # Unit tests
│   └── conftest.py           # Test configuration
├── volume/                   # Persistent storage
│   ├── config/               # Configuration files
│   ├── data/                 # Data directory
│   ├── kb/                   # Knowledge base storage
│   │   ├── search/           # Search indices
│   │   │   ├── sparse_idx/   # Sparse search index
│   │   │   └── graph_idx/    # Graph search index
│   │   ├── archive/          # Archived documents
│   ├── logs/                 # Log files
│   ├── sandbox/              # Sandboxed execution space
│   │   ├── bash/             # Bash sandbox
│   │   ├── browser/          # Web browser sandbox
│   │   ├── files/            # File operation sandbox
│   │   └── python/           # Python sandbox
│   └── temp/                 # Temporary storage
├── Containerfile            # Container definition
├── podman-compose.yml       # Container orchestration
├── pyproject.toml           # Python project configuration
├── uv.lock                  # Dependency lock file
├── pytest.ini               # Test configuration
└── README.md                # Project documentation

每个管理器都遵循一致的设计模式:

  • .from_env() 类方法,用于基于环境进行初始化
  • 异步执行方法,用于执行非阻塞操作
  • 严格的输入验证和错误处理
  • 所有操作均以安全为先

安全措施

Container-MCP 实施多层安全防护:

  1. 容器隔离:使用 Podman/Docker 进行容器隔离
  2. AppArmor 配置文件:对 bash 和 Python 执行实施精细访问控制
  3. Firejail 沙盒:提供额外的进程隔离
  4. 资源限制:限制内存、CPU 和执行时间
  5. 路径遍历防护:验证并规范化所有文件路径
  6. 允许的扩展名限制:控制可访问的文件类型
  7. 网络限制:控制可访问的域名
  8. 最小权限:各组件仅以必要的最低权限运行

安装

前提条件
  • 安装了 Podman 或 Docker 的 Linux 系统
  • Python 3.12+
  • Firejail(apt install firejail 或 dnf install firejail)
  • AppArmor(apt install apparmor apparmor-utils 或 dnf install apparmor apparmor-utils)
快速开始

最快的入门方式是使用一体化脚本:

git clone https://github.com/54rt1n/container-mcp.git
cd container-mcp
chmod +x bin/00-all-in-one.sh
./bin/00-all-in-one.sh
分步安装

你也可以逐项执行安装步骤:

  1. 初始化项目:

    ./bin/01-init.sh
    
  2. 构建容器:

    ./bin/02-build-container.sh
    
  3. 设置环境:

    ./bin/03-setup-environment.sh
    
  4. 运行容器:

    ./bin/04-run-container.sh
    
  5. 运行测试(可选):

    ./bin/05-run-tests.sh
    

使用方法

容器运行后,你可以使用任何 MCP 客户端实现连接到它。服务将在 http://localhost:8000 或配置中指定的端口上提供。

重要: 配置 MCP 客户端时,必须将端点 URL 设置为 http://127.0.0.1:<port>/sse(其中 <port> 默认为 8000,或为你配置的端口)。/sse 路径是正确进行服务器发送事件通信所必需的。

Python 客户端示例
from mcp.client.sse import sse_client
from mcp import ClientSession
import asyncio

async def main():
    # Connect to the Container-MCP server
    # Note the /sse endpoint suffix required for SSE communication
    sse_url = "http://127.0.0.1:8000/sse"  # Or your configured port
    
    # Connect to the SSE endpoint
    async with sse_client(sse_url) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
            
            # Discover available tools
            result = await session.list_tools()
            print(f"Available tools: {[tool.name for tool in result.tools]}")
            
            # Execute a Python script
            python_result = await session.execute_tool(
                "system_run_python",
                {"code": "print('Hello, world!')\nresult = 42\n_ = result"}
            )
            print(f"Python result: {python_result}")
            
            # Execute a bash command
            bash_result = await session.execute_tool(
                "system_run_command",
                {"command": "ls -la"}
            )
            print(f"Command output: {bash_result['stdout']}")

if __name__ == "__main__":
    asyncio.run(main())

配置

可以通过环境变量配置 Container-MCP,这些变量可在 volume/config/custom.env 中设置:

服务配置
# MCP Server Configuration
MCP_HOST=127.0.0.1
MCP_PORT=9001
DEBUG=true
LOG_LEVEL=INFO
Bash 管理器配置
# Bash Manager Configuration
BASH_ALLOWED_COMMANDS=ls,cat,grep,find,echo,pwd,mkdir,touch
BASH_TIMEOUT_DEFAULT=30
BASH_TIMEOUT_MAX=120
Python 管理器配置
# Python Manager Configuration
PYTHON_MEMORY_LIMIT=256
PYTHON_TIMEOUT_DEFAULT=30
PYTHON_TIMEOUT_MAX=120
文件管理器配置
# File Manager Configuration 
FILE_MAX_SIZE_MB=10
FILE_ALLOWED_EXTENSIONS=txt,md,csv,json,py
Web 管理器配置
# Web Manager Configuration
WEB_TIMEOUT_DEFAULT=30
WEB_ALLOWED_DOMAINS=*
知识库管理器配置
# Knowledge Base Manager Configuration
CMCP_KB_STORAGE_PATH=/app/kb
KB_TIMEOUT_DEFAULT=30
KB_TIMEOUT_MAX=120

# Search Configuration
CMCP_KB_SEARCH_ENABLED=true
CMCP_KB_SPARSE_INDEX_PATH=/app/kb/search/sparse_idx
CMCP_KB_GRAPH_INDEX_PATH=/app/kb/search/graph_idx
CMCP_KB_RERANKER_MODEL=mixedbread-ai/mxbai-rerank-base-v1
CMCP_KB_SEARCH_RELATION_PREDICATES=references
CMCP_KB_SEARCH_GRAPH_NEIGHBOR_LIMIT=1000

# Tool Enable/Disable
TOOLS_ENABLE_KB=true
列表管理器配置
# List Manager Configuration
CMCP_LIST_STORAGE_PATH=/app/lists
TOOLS_ENABLE_LIST=true
市场管理器配置
# Market Manager Configuration
MARKET_TIMEOUT_DEFAULT=30
MARKET_TIMEOUT_MAX=60
TOOLS_ENABLE_MARKET=true
RSS 管理器配置
# RSS Manager Configuration
RSS_TIMEOUT_DEFAULT=15
RSS_TIMEOUT_MAX=30
RSS_USER_AGENT=container-mcp/1.0
TOOLS_ENABLE_RSS=true

开发

设置开发环境
  1. 创建 Python 虚拟环境:

    python3.12 -m venv .venv
    source .venv/bin/activate
    
  2. 安装依赖项:

    pip install -r requirements-dev.txt
    
  3. 以开发模式安装软件包:

    pip install -e .
    
运行测试
# Run all tests
pytest

# Run only unit tests
pytest tests/unit

# Run only integration tests
pytest tests/integration

# Run with coverage report
pytest --cov=cmcp --cov-report=term --cov-report=html
开发服务器

要以开发模式运行 MCP 服务:

python -m cmcp.main --test-mode

许可证

本项目采用 Apache License 2.0 许可。

作者

Martin Bukowski

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。