Skip to main content
Glama
nezolder

Civil 3D MCP Server

by nezolder

Civil 3D MCP 服务器 — 动态 Roslyn 分支

一个 MCP 服务器,使 AI 助手能够直接在 Autodesk Civil 3D 内部编写并执行 C# 代码。它不是提供一大组固定工具,而是由 AI 生成特定任务的代码,并借助 Civil 3D API 访问权限运行。

项目范围与血统

本分支保留了动态 Roslyn/C# 执行模型,并刻意保持仅三个 MCP 工具的较小公共表面。其当前兼容性基线为 Autodesk Civil 3D 2025,本地工作侧重于可靠性、安全性、可衡量的效率以及可复用的 Civil 3D 技能。其他 Civil 3D 版本可通过单独验证的兼容性工作后续添加。

本项目衍生自 barbosaihan/civil3d-mcp。SantosSjba/mcp-to-c3d 被评估用于某些经过测试验证的想法,而 Sacred-G/Civil3D-mcp 仅作为架构参考。详细的归属与许可边界请参阅 PROVENANCE.md。

本独立项目与 Autodesk 无关联,也未获得其认可。Autodesk 程序集及其他专有 Civil 3D 文件不包含在内。

Related MCP server: Civil 3D MCP Server

架构

┌─────────────────┐     stdio      ┌──────────────────┐     TCP/JSON-RPC    ┌──────────────────┐
│   AI Assistant   │ ◄────────────► │  MCP Server (TS) │ ◄──────────────────► │  Civil 3D Plugin │
│ (Claude, Cline)  │               │   3 meta-tools    │     port 8080       │  Roslyn Engine   │
└─────────────────┘               └──────────────────┘                      └──────────────────┘
                                         │                                         │
                                    Skills Library                           C# Code Execution
                                   (.skill.md files)                      (full Civil 3D API)

3 个元工具

工具

用途

安全性

civil3d_execute

执行具有写入权限的 C# 代码;提交后可选择保存

⚠️ 修改图形

civil3d_query

执行 C# 代码只读(不提交)

✅ 无副作用

civil3d_skills

浏览/搜索/读取代码技能模板;api_lookup 搜索已加载的公共 Civil 3D API 元数据

✅ 仅元数据

工作原理

  1. AI 读取技能 → 获取带文档说明的 C# 代码模板

  2. AI 调整代码 → 填入参数、组合模式

  3. AI 发送代码 → 通过 civil3d_execute 或 civil3d_query

  4. Roslyn 编译并运行 → 在 Civil 3D 内部,具有完整 API 访问权限

  5. 结果以 JSON 返回 → 返回给 AI

交互示例

User: "What surfaces are in my drawing?"

AI: Uses civil3d_query with:
  var surfaces = new List<object>();
  foreach (ObjectId id in CivilDoc.GetSurfaceIds()) {
    var s = Transaction.GetObject(id, OpenMode.ForRead) as TinSurface;
    surfaces.Add(new { s.Name, s.Layer });
  }
  return surfaces;

Result: [{ "Name": "EG", "Layer": "C-TOPO-EG" }, ...]

技能库

civil3d_skills 还支持 action: "api_lookup",用于对已加载的允许列表 Civil 3D 宿主程序集中的公共类型和成员名称/签名进行有界、只读的搜索。它不会加载程序集、运行 C# 代码或访问当前图形。提供查询条件,并可选择提供程序集、命名空间前缀和结果数量限制。

技能是 skills/ 目录中带文档说明的 C# 代码模板:

skills/
├── surfaces/           # Surface operations
├── alignments/         # Alignment + station/offset
├── points/             # COGO points
├── geometry/           # Lines, polylines, text
├── drawing/            # Drawing info
└── workflows/          # Complex multi-object operations

脚本全局变量

通过 civil3d_execute 或 civil3d_query 执行的代码可访问:

全局变量

类型

描述

Document

Document

当前 AutoCAD 文档

CivilDoc

CivilDocument

当前 Civil 3D 文档

Database

Database

文档数据库

Transaction

Transaction

当前事务

Editor

Editor

文档编辑器

所有 Civil 3D 命名空间均自动导入。

提交 civil3d_execute 事务会更改打开的图形,但本身不会将 DWG 文件写入磁盘。当完成的更改也应保存时,请设置 saveDrawing: true。插件仅在脚本事务和文档锁关闭后才保存;脚本不得自行调用 Database.SaveAs 或排队 QSAVE。保存请求使用单独的 10 分钟默认超时,且不会自动重试。

设置

1. 构建 MCP 服务器

npm install && npm run build

2. 构建插件

# Copy DLLs from Civil 3D to C_References/ (see C_References/README.md)
cd plugin/Civil3dMcpPlugin
dotnet build

3. 在 Civil 3D 中加载

NETLOAD → select Civil3dMcpPlugin.dll
C3DMCPSTATUS → verify running

4. 配置 AI

{
  "mcpServers": {
    "civil3d": {
      "command": "node",
      "args": ["/path/to/civil3d-mcp/build/index.js"]
    }
  }
}

环境变量

变量

默认值

描述

CIVIL3D_HOST

localhost

插件主机

CIVIL3D_PORT

8080

插件端口

CIVIL3D_COMMAND_TIMEOUT

120000

执行超时(毫秒)

CIVIL3D_SAVE_TIMEOUT

600000

带 saveDrawing: true 的执行请求的超时(毫秒)

LOG_LEVEL

info

日志级别

基准测试

阶段 2A 的与主机无关的记录器、阶段 2A.1 的可选内部实时跟踪契约,以及阶段 2A.2 的只读实时运行器,均记录在 benchmark/README.md 中。它们均不添加 MCP 工具、队列或重试机制;2A.2 运行器仅在显式启动时才能调用其固定的只读查询。

结构化错误(阶段 2B.1)

civil3d_query 和 civil3d_execute 保留其现有的文本错误内容和 isError: true,同时返回带有 civil3d-mcp-error/v1 模式的 structuredContent。稳定的错误字段为 code、category、message、source、outcome 和 retryable。命令超时或发送后连接丢失具有 outcome: "unknown" 和 retryable: false;服务器永远不会自动重试。成功响应和三个工具的公共表面保持不变。

私有 TCP 帧协议(阶段 2C.1)

每个 localhost TCP 连接承载一个 UTF-8 JSON-RPC 请求和一个响应。每个 JSON 主体后跟 LF,且限制为 8 MiB(以 UTF-8 字节计,不含 LF)。Node 客户端仍接受先前插件在完整 JSON 主体后跟有序连接关闭时的无帧响应。过大的请求在写入前即被拒绝;过大或格式错误的响应以及中断的连接会产生不可重试的结构化传输错误。如果执行已完成但插件无法返回过大的结果,则报告的结果为 unknown。

操作审计日志与写入幂等性(阶段 2I.1 / 2I.2)

在默认的 info 日志级别下,每个被接受的 civil3d_query 和 civil3d_execute 操作都会发出一个有界的 stderr 审计事件。它包含一个新的不透明操作 ID、工具名称、C# 源代码的 SHA-256 和 UTF-8 字节长度、成功/错误状态以及耗时毫秒数;错误仅添加稳定的 code/category/source/outcome 字段。审计事件从不包含调用方代码、描述、图形身份、结果或错误消息。

civil3d_execute 还接受一个可选的不透明 idempotencyKey(1–128 个 ASCII 字母、数字、.、_、:、-)。在一个插件会话中,它将键绑定到 UTF-8 C# SHA-256、规范化后的 expectedDrawing 身份以及 saveDrawing 选择。重复项会被拒绝为进行中、冲突或已提交;已提交的条目不保留结果,调用方必须通过只读查询进行对账。保存失败发生在内存写入提交之后,因此其键保留为已完成状态,以防止意外的重复修改。会话最多保留 256 个已完成的键,按确定性规则淘汰最旧的。这既不增加持久性,也不增加自动重试或恰好一次语义。

安全性

Roslyn 沙箱阻止:

  • 进程执行(Process.Start)

  • 文件删除(File.Delete)

  • 网络请求(HttpClient、Sockets)

  • 注册表访问

  • 动态程序集加载

所有 Civil 3D API 操作均被允许。

此正则表达式沙箱是纵深防御,而非信任边界。两个代码工具都会接收可变的 Civil 3D 和 AutoCAD API 对象;civil3d_query 会跳过宿主的提交事务,但无法保证任意动态 C# 代码无副作用。仅运行受信任且经审批门控的代码。回环 TCP 可防止远程网络访问,但不会对其他本地进程进行身份验证。

许可证

MIT

Available Tools

3 tools
civil3d_executeA

Execute C# code in Civil 3D with write access. The code runs inside a committed transaction. Available globals: Document, CivilDoc, Database, Transaction, Editor. All Civil 3D namespaces are auto-imported. Return a value to get results back as JSON. Use this for operations that MODIFY the drawing (create, edit, delete objects). expectedDrawing must come from a prior read-only identity query. To persist the drawing file, set saveDrawing=true; do not call Database.SaveAs or queue QSAVE from the C# code.

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYesC# code to execute. Has access to Document, CivilDoc, Database, Transaction, Editor. Example: var id = TinSurface.Create(Database, "MySurface"); return new { success = true };
descriptionNoOptional human-readable summary; excluded from operation audit logs.
saveDrawingNoWhen true, save the currently named DWG after the write transaction commits and wait for completion. Use this instead of Database.SaveAs or Document.SendStringToExecute("QSAVE") in code. An unsaved drawing must first be named in Civil 3D.
idempotencyKeyNoOptional opaque session key. Reuse it only to manually reconcile an uncertain outcome; use a new key for an intentional new write.
expectedDrawingYesExpected active drawing identity checked immediately before Civil API access.

TDQS

A4.7/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and does well: it notes the committed transaction, available globals, JSON return, drawing identity check, and save workflow. It does not mention exception handling or failure rollback, but that is a minor gap for a code-execution tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact and front-loaded with the core purpose, then elaborates on key parameters and constraints. It is not overly verbose, though bullet formatting could improve scannability; still, every sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex code-execution tool with no output schema, the description explains available globals, return format, drawing identity requirements, save behavior, and sibling distinction. No critical operational detail is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, yet the description adds significant context: expectedDrawing provenance and check timing, saveDrawing conditions (must be named), idempotencyKey purpose, and an example for code. It clearly enhances schema-only information.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a precise purpose: executing C# code with write access in Civil 3D. It explicitly scopes the tool to modifying the drawing ('Use this for operations that MODIFY the drawing'), which distinguishes it from the read-only sibling civil3d_query.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It provides clear usage criteria: use for modifications, not for reads; requires expectedDrawing from a prior civil3d_query; and warns against calling Database.SaveAs or queuing QSAVE, directing the user to the saveDrawing parameter instead. This fully covers when and how to use it versus alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

civil3d_queryA

Execute C# code in Civil 3D in READ-ONLY mode (no changes saved). Available globals: Document, CivilDoc, Database, Transaction, Editor. All Civil 3D namespaces are auto-imported. Return a value to get results as JSON. Use this for querying data: listing objects, getting properties, analyzing surfaces, etc. Omit expectedDrawing only to bootstrap Database.Filename and Database.FingerprintGuid; otherwise supply it to guard the active drawing.

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYesC# code to query data. Has access to Document, CivilDoc, Database, Transaction, Editor. Example: var surfaces = new List<object>(); foreach (ObjectId id in CivilDoc.GetSurfaceIds()) { var s = Transaction.GetObject(id, OpenMode.ForRead) as TinSurface; surfaces.Add(new { s.Name, s.Layer }); } return surfaces;
expectedDrawingNoExpected active drawing identity checked immediately before Civil API access.

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and does substantial work: it discloses read-only semantics ('no changes saved'), available globals (Document, CivilDoc, Database, Transaction, Editor), auto-imported namespaces, the JSON return mechanism, and the expectedDrawing guard vs. bootstrap behavior. It does not cover error behavior for failed compilation or thrown exceptions at runtime, which is a notable gap for a code-execution tool, but the disclosed traits are rich.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three sentences, each earning its place: purpose/globals/return semantics, when-to-use, and the expectedDrawing rule. The first sentence is dense but not wasteful; the most critical differentiator (READ-ONLY) is front-loaded before supporting details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex code-execution tool with no annotations and no output schema, the description covers the essentials: execution mode, environment globals, namespaces, return format, and the identity-guard parameter semantics. The main omissions are error/exception behavior and the exact failure mode when expectedDrawing mismatches, which an agent invoking arbitrary C# code would benefit from knowing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description adds genuine value beyond the schema by explaining when to omit expectedDrawing entirely — 'Omit expectedDrawing only to bootstrap Database.Filename and Database.FingerprintGuid; otherwise supply it to guard the active drawing' — a semantic the schema's field descriptions do not convey.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource: 'Execute C# code in Civil 3D in READ-ONLY mode (no changes saved).' It further scopes the tool with 'Use this for querying data: listing objects, getting properties, analyzing surfaces, etc.', which clearly differentiates it from the sibling civil3d_execute. An agent can tell immediately what this tool does and how it differs.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

'Use this for querying data' is an explicit when-to-use statement with concrete examples. The READ-ONLY framing implies that mutations belong to the sibling civil3d_execute, though it never names that alternative or states a when-not-to-use condition explicitly, so it stops short of a full 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

civil3d_skillsA

Browse and read Civil 3D code skills (documented C# code templates). Use 'list' to see available skills, 'search' to find by keyword, 'get' to read the full skill with code template, or 'api_lookup' to search public metadata from already-loaded Civil 3D host assemblies. Skills are pre-built C# patterns you can adapt and execute via civil3d_execute or civil3d_query.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum list/search/api_lookup results to return (integer 1-50; default 20)
queryNoSearch query for 'search' or 'api_lookup' action
actionYeslist = browse skill metadata, search = find by keyword, get = read full skill, api_lookup = read-only public API metadata search
cursorNoOpaque nextCursor from a prior list/search call with the same filters
assemblyNoAllowlisted loaded host assembly filter for api_lookup
categoryNoFilter by category (surfaces, alignments, points, etc.)
namespaceNoNamespace prefix filter for api_lookup
skillNameNoSkill name for 'get' action

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the behavioral disclosure burden. It clearly labels the tool as read-only ('Browse and read', 'read-only public API metadata search'), implying no state changes. It also notes that execution happens via sibling tools, which further clarifies that this tool itself does not modify anything. The absence of side-effect warnings is acceptable given the read-only framing.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three concise sentences, each adding critical information: the core purpose, the list of actions, and the relationship to sibling tools. It front-loads the main purpose and avoids redundancy or filler. Every sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a read-only tool with four actions, the description is nearly complete. It explains the actions, implies the output (list of skills, search results, full skill content, API metadata), and points to the execution siblings. While it doesn't detail pagination or output structure, those are typically understood and the schema covers cursor details. The description is sufficient for an agent to call it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so all eight parameters have descriptions in the schema. The tool description adds contextual meaning (e.g., what 'get' does, that api_lookup is read-only) but does not explain parameter syntax or constraints beyond the schema. This meets the baseline of 3 but does not exceed it.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb-resource pair ('Browse and read Civil 3D code skills') and immediately enumerates the four supported actions (list, search, get, api_lookup). It also distinguishes itself from the sibling tools by noting that skills 'can be adapted and execute via civil3d_execute or civil3d_query.' This clearly sets its scope apart.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explains the tool's role as a browsing/reading layer and explicitly points to the sibling tools for execution. It also differentiates between read actions (list/search/get) and the read-only metadata api_lookup. While it doesn't list explicit 'when not to use' scenarios, the purpose is clear enough for an agent to decide between this and its siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 3 tool updatesv1.0.0
    • First observedcivil3d_execute
    • First observedcivil3d_query
    • First observedcivil3d_skills

TDQS

A4.4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clear, non-overlapping purpose: execute for write operations, query for read-only operations, and skills for browsing code templates. The read/write distinction is explicitly stated, so agents should not confuse execute and query.

Naming Consistency4/5

All tools share the civil3d_ prefix and snake_case, but the suffixes mix verbs (execute, query) with a noun (skills), making it not a strictly consistent verb_noun pattern. The naming is still predictable and readable.

Tool Count5/5

Three tools is a well-scoped set for a server that provides arbitrary C# execution capabilities; each tool serves a distinct and necessary function. The count falls within the typical 3-15 range.

Completeness5/5

The combination of execute and query covers the full range of Civil 3D operations (create, edit, delete, query), and skills fills the learning gap. No obvious missing functionality for the stated purpose.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    C
    maintenance
    Enables AI assistants to interact with Autodesk Civil 3D through natural language, supporting tools for surfaces, alignments, profiles, corridors, pipe networks, COGO points, and AutoCAD geometry.
    9
    3
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Lets any MCP-compatible AI assistant read and edit Autodesk Civil 3D drawings through tools for alignments, surfaces, corridors, pipe networks, quantity takeoff, and cut/fill, using a local bridge plugin and named pipes.
    MIT