容器化模型上下文协议

Container-MCP是一个基于容器的安全实现,用于在模型上下文协议(MCP)下执行大语言模型请求的工具,提供沙盒环境以安全执行代码、运行命令、访问文件和进行网络操作。

  • by 54rt1n
  • Python
  • 本地部署
  • 22 星标
  • 更新于
在 GitHub 查看 54rt1n/container-mcp

使用说明

集装箱MCP

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

概述

容器MCP提供了一个沙盒环境,用于安全执行代码、运行命令、访问文件和执行大型语言模型所请求的web操作。它实现了MCP协议,将这些功能作为AI系统可以安全地发现和调用的工具。

该架构使用具有多层安全性的特定于域的管理器模式,以确保工具在具有适当限制的隔离环境中执行,保护主机系统免受潜在有害操作的影响。

主要特点

  • 多层安全

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

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

    • BashManager:安全命令执行
    • PythonManager:沙盒Python代码执行
    • FileManager:安全的文件操作
    • WebManager:安全的网页浏览和抓取
    • KnowledgeBaseManager:具有语义搜索的结构化文档存储
    • ListManager:有组织的清单和收集管理
    • MarketManager:通过雅虎财经获取股票和加密货币数据
    • RssManager:RSS和Atom提要获取
  • 可配置环境

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

可用工具

系统操作

system_run_command

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

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

system_run_python

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

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

system_env_var

获取环境变量值。

  • 参数:
    • var_name (字符串,可选):要检索的特定变量
  • 退货:
    • 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):服务器详细信息(名称、主机、端口、平台、python_version)
    • system (对象):系统指标(cpu_percent、memory_percent和disk_percent)
    • managers (对象):每个管理器的状态(启用/禁用)
{
  "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 (字符串,必填):文件路径(相对于沙盒根)
    • encoding (字符串,可选):文件编码(默认:“utf-8”)
  • 退货:
    • content (string):文件内容
    • size (整数):文件大小(字节)
    • modified (float):最后修改的时间戳
    • success (boolean):读取是否成功
{
  "content": "This is the content of the file.",
  "size": 31,
  "modified": 1673452800.0,
  "success": true
}

fs_write

将内容安全地写入文件。

  • 参数:
    • path (字符串,必填):文件路径(相对于沙盒根)
    • content (string,必填):要写的内容
    • encoding (字符串,可选):文件编码(默认:“utf-8”)
  • 退货:
    • success (boolean):写入是否成功
    • path (string):写入文件的路径
{
  "success": true,
  "path": "data/myfile.txt"
}

fs_list

安全地列出目录的内容。

  • 参数:
    • path (字符串,可选):目录路径(默认:“/”)
    • pattern (字符串,可选):用于过滤文件的Glob模式
    • recursive (布尔值,可选):是否递归列出(默认值: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 (字符串,必填):源文件路径
    • destination_path (字符串,必填):目标文件路径
  • 退货:
    • 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

将统一的差异补丁应用于沙盒文件系统中的文件。

  • 参数:
    • path (字符串,必填):要修补的文件的路径(相对于沙盒根)
    • diff (字符串,必填):要应用的统一差异内容
  • 退货:
    • success (boolean):补丁是否成功应用
    • path (string):修补文件的路径
    • lines_applied (整数):更改的行数
    • new_size (整数):新文件大小(字节)
    • error (string):补丁失败时的错误消息
{
  "success": true,
  "path": "src/main.py",
  "lines_applied": 5,
  "new_size": 1248,
  "error": null
}

Web操作

web_search

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

  • 参数:
    • 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 (字符串,可选):CSS选择器,用于定位特定内容
    • output_format (字符串,可选):使用 "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 (字符串,必填):浏览会话的起始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

  • 命名空间:最高级别的组织单位(例如“项目”、“研究”)
  • 收集名称空间内的主要类别(例如,“文档”、“注释”)
  • 子集:可选嵌套类别(例如“api”、“tutorials”)
  • 名字:文档标识符(例如“入门”、“用户指南”)

示例:

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

kb_create_document

在知识库中创建具有可选元数据和内容的新文档。

  • 参数:
    • uri (字符串,必填):文档URI格式为“kb://namespace/collection[/subcollection]*/name”
    • metadata (对象,可选):文档元数据(默认值:{})
    • content (字符串,可选):文档内容(允许单步创建和写入)
  • 退货:
    • 包含创建详细信息的完整文档索引对象
  • 备注:您可以通过提供 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 (字符串,必填):文档URI
    • content (字符串,必填):文档内容
    • force (布尔值,可选):是否覆盖现有内容(默认值: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 (字符串,可选):文档URI。如果省略,则列出所有文档。
    • recursive (布尔值,可选):是否递归列出(默认值:true)
    • include_content (布尔值,可选):是否包含文档内容(默认值:false)
    • include_index (boolean,可选):是否包含文档元数据(默认值:false)
  • 退货:
    • 根据请求的组件记录数据。在三种模式下运行:
      • 列表模式:何时 uri 省略,返回文档URI列表
      • bulk_read模式:何时 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,必填):要执行的操作(“添加”或“删除”)
    • triple_type (字符串,必填):三元组类型(“首选项”、“引用”或“元数据”)
    • uri (字符串,必填):源文档URI
    • predicate (string,必填):三元组的谓词
    • object (string,可选):三元组的对象(用于首选项和元数据)
    • ref_uri (字符串,可选):引用的文档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 (字符串,可选):用于语义搜索和重新排序的文本查询
    • seed_uris (数组,可选):启动用于图形扩展的完整URI(kb://namespace/collection/name)
    • root_uri (字符串,可选):用于范围搜索的部分URI(kb://namespace或kb://namespace/collection)
    • expand_hops (整数,可选):要扩展的关系跃点数(默认值:0)
    • filter_uris (数组,可选):要从结果中排除的URI
    • relation_predicates (数组,可选):在图遍历过程中要遵循的谓词(默认值:[“references”])
    • top_k_sparse (整数,可选):要检索的稀疏搜索结果数(默认值:50)
    • top_k_rerank (整数,可选):重新排名后的最终结果数量(默认值:10)
    • include_content (布尔值,可选):是否包含文档内容(默认值:false)
    • include_index (boolean,可选):是否包含文档元数据(默认值:false)
    • use_reranker (布尔值,可选):是否使用语义重排序(默认值: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 (对象,必填):特定于操作的选项
      • 对于 "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"
  }
}

清单的操作

列表系统为任务、笔记、购物和一般收藏提供基于组织模式的列表管理。列表支持各种项目状态,可以标记为组织。

项目状态

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

列表类型

列表可以是以下之一: todo, shopping, notes, checklist, project, reading, ideas

list_create

为任务、笔记、购物或任何收藏创建新的有组织列表。

  • 参数:
    • name (字符串,必填):列表的内部名称(用于文件名)
    • title (字符串,可选):显示列表的标题
    • list_type (字符串,可选):列表类型(默认值:“todo”)
    • description (字符串,可选):可选描述
    • tags (数组,可选):组织标签
    • properties (对象,可选):自定义用户定义的特性
  • 退货:
    • success (boolean):创建是否成功
    • name (string):列表名称
    • metadata (对象):标题、类型、创建的时间戳、属性
    • 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 (布尔值,可选):是否在响应中包含项目(默认值:true)
    • summary_only (boolean,可选):仅返回不带项目的摘要统计信息(默认值:false)
    • status_filter (字符串,可选):按状态筛选项目(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
    • tag_filter (数组,可选):按标签筛选项目(项目必须具有所有指定的标签)
  • 退货:
    • 当 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 (字符串,必填):要执行的操作(“添加”、“更新”或“删除”)
    • item_text (字符串,可选):项目文本(“添加”需要,“更新”可选)
    • item_index (整数,可选):项目索引(“更新”和“删除”需要)
    • status (字符串,可选):项目状态(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
    • tags (数组,可选):项目的标签
    • properties (对象,可选):自定义特性
  • 退货:
    • success (boolean):操作是否成功
    • action (string):执行的操作
    • item (对象):受影响的项目详细信息

添加项目:

{
  "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 (字符串,可选):新标题
    • list_type (字符串,可选):新列表类型
    • description (字符串,可选):新描述
    • tags (数组,可选):新标签(替换现有标签)
    • author (字符串,可选):新作者
    • properties (对象,可选):自定义属性(与现有属性合并)
  • 退货:
    • success (boolean):更新是否成功
    • name (string):列表名称
    • metadata (对象):更新的元数据
{
  "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 (整数):列表中的项目数
    • 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 (数组,可选):要搜索的特定列表(如果省略,则搜索所有列表)
    • search_in (数组,可选):搜索位置:“文本”、“标签”或两者都有(默认值:[“文本”])
    • case_sensitive (boolean,可选):搜索是否区分大小写(默认值:false)
  • 退货:
    • matches (array):具有列表上下文的匹配项列表
    • total_matches (整数):总匹配数
    • lists_searched (整数):搜索的列表数
    • search_options (对象):应用的搜索参数
{
  "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
  }
}

市场运作

市场系统使用雅虎财经提供股票和加密货币的财务数据查询。

market_query

通过基本面、新闻和趋势分析查询股票或加密货币价格。

  • 参数:
    • symbol (字符串,必填):股票/加密货币符号(例如,“AAPL”、“BTC-USD”、“TSLA”)
    • period (字符串,可选):趋势指标的历史时期(默认值:“1y”)
    • interval (字符串,可选):历史数据间隔(默认值:“1d”)
    • news_count (整数,可选):要返回的最近新闻项数(默认值:5)
  • 退货:
    • symbol (string):查询符号
    • name (string):公司/资产名称
    • price (浮动):当前价格
    • change (浮动):价格变动
    • change_percent (浮动):百分比变化
    • volume (整数):交易量
    • market_cap (整数):市值
    • currency (string):货币代码
    • timestamp (字符串):ISO格式时间戳
    • fundamentals (对象):收益、市盈率、股息、利润率
    • news (array):最近的新闻
    • trend (对象):移动平均线、RSI、波动率、历史回报率
    • success (boolean):查询是否成功
    • error (string):查询失败时出现错误消息
{
  "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 (string):提要的标题
    • feed_link (string):链接到提要的网站
    • items (数组):馈送项目,每个项目具有:
      • title (string):项目标题
      • link (字符串):项目URL
      • published (string):发布日期
      • summary (string):项目摘要/描述
    • item_count (整数):返回的项目数
    • success (boolean):取是否成功
    • error (string):如果获取失败,则显示错误消息
{
  "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
}

执行环境

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

集装箱环境

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

  • 基本图像:Ubuntu 24.04
  • 用户:非root ubuntu用户
  • python: 3.12
  • 网络:仅限于本地主机绑定
  • 文件系统:用于配置、数据和日志的卷装载
  • 安全:AppArmor、Seccomp和能力限制

Bash执行环境

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

  • 允许的命令:仅限于在中配置的安全命令 BASH_ALLOWED_COMMANDS
  • 火狱沙盒:限制文件系统访问的进程隔离
  • AppArmor配置文件:细粒度访问控制
  • 资源限制:
    • 执行超时(默认:30s,最大:120s)
    • 仅限于沙盒目录访问
  • 网络:无法访问网络
  • 文件系统:对数据的只读访问,对沙盒的读写访问

允许的命令示例:

ls, cat, grep, find, echo, pwd, mkdir, touch

Python执行环境

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

  • Python版本: 3.12
  • 内存限制:可配置的内存上限(默认值:256MB)
  • 执行超时:可配置的时间限制(默认:30秒,最大:120秒)
  • AppArmor配置文件:限制对系统资源的访问
  • 火狱沙盒:过程隔离
  • 能力:所有功能均已下降
  • 网络:无法访问网络
  • 可用的库:仅标准库
  • 输出捕获:stdout/stderr已重定向并清理
  • 资源控制:强制执行CPU和内存限制

文件系统环境

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

  • 基础目录:所有操作仅限于沙箱根
  • 路径验证:对所有路径进行规范化并检查遍历尝试
  • 大小限制:强制的最大文件大小(默认值:10MB)
  • 扩展控制:只允许使用扩展名(默认:txt、md、csv、json、py)
  • 权限控制:强制执行适当的读/写权限
  • 孤立:无法访问主机文件系统

网络环境

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

  • 域控制:允许域的可选白名单
  • 超时控制:可配置的操作超时
  • 浏览器控件:通过Playwright无头浏览器进行全渲染
  • 报废控制:通过请求简单抓取/BeautifulSoup
  • 内容消毒:所有内容都经过解析和净化
  • 网络隔离:通过容器分离网络命名空间

知识库环境

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

  • 分级组织:按名称空间/集合/名称结构组织的文档
  • 元数据管理:具有RDF风格三元组的丰富元数据支持
  • 语义搜索:具有稀疏索引和语义重排序的全文搜索
  • 图表关系:具有关系遍历的文档引用
  • 路径验证:严格的路径验证和规范化
  • 搜索索引:分离稀疏索引和图索引以获得最佳性能
  • 超时控制:可配置的操作超时(默认值:30秒,最大值:120秒)
  • 孤立:知识库操作仅限于配置的存储路径

列表环境

列表环境提供有组织的收集管理:

  • 组织模式格式:列表存储为组织模式文件以便于移植
  • 状态跟踪:项目支持多种状态(TODO、DONE、WAITING、CANCELLED、NEXT、SOMEDAY)
  • 标记:项目和列表支持灵活组织的标签
  • 档案:为安全起见,已删除的列表已存档
  • 搜索:按文本和标签进行跨列表搜索
  • 孤立:列出仅限于配置的存储路径的操作

市场环境

市场环境提供了对财务数据的受控访问:

  • 数据源:雅虎财经股票和加密货币
  • 超时控制:可配置超时(默认值:30秒,最大值:60秒)
  • 数据类型:报价、基本面、新闻和趋势分析

RSS环境

RSS环境提供提要获取功能:

  • 饲料类型:支持RSS和Atom提要
  • 超时控制:可配置超时(默认值:15秒,最大值:30秒)
  • 用户代理:可配置的用户代理字符串
  • 项目限制:每次取件可配置的最大项目数

建筑

该项目采用模块化架构:

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() 基于环境初始化的类方法
  • 非阻塞操作的异步执行方法
  • 强大的输入验证和错误处理
  • 所有操作的安全第一方法

安全措施

容器MCP实现了多层安全:

  1. 集装箱隔离:使用Podman/Docker进行容器隔离
  2. AppArmor配置文件:bash和Python执行的细粒度访问控制
  3. 消防监狱沙盒:附加过程隔离
  4. 资源限制:内存、CPU和执行时间限制
  5. 路径穿越预防:验证并规范所有文件路径
  6. 允许的扩展限制:控制可以访问的文件类型
  7. 网络限制:控制可以访问哪些域
  8. 最小特权:组件以最低限度的必要权限运行

安装

先决条件

  • 使用Podman或Docker的Linux系统
  • Python 3.12+
  • 消防监狱(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())

配置

容器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许可证2.0获得许可。

作者

马丁·布考斯基