AI 乱写代码怎么破?使用 Context7 MCP Server 让 AI 写出靠谱代码!

简介: 本文通过实际案例演示了如何利用 Context7 MCP Server 解决 AI 编程助手中的代码幻觉问题和使用过时 API 的问题。借助 Context7 获取最新、最准确的代码建议,显著提升了 AI 生成的代码质量,从而有效提高了开发效率。

作为一名开发者,你是否经常遇到这样的困扰?AI 编程助手虽然强大,但仍然存在严重的代码幻觉,经常编造根本不存在的 API 接口。此外,目前主流的大语言模型(如 OpenAI,Claude,DeepSeek)的训练数据往往滞后于技术的更新,导致生成的代码常常基于已经废弃的旧版 API。结果就是,虽然 AI 可以快速生成代码,但调试和排错却耗费了大量时间,反而拖慢了开发进度。

Context7 的优点

Context7 的出现正是为了解决上面的痛点,Context7 充当了编程提示与实时软件文档之间的桥梁。每当被调用时,Context7 会从官方源头获取最新的、版本特定的文档和相关代码示例,提供给 AI 编程助手,将这些信息注入到 LLM 的上下文中,从而有效提高 LLM 生成代码的质量。Context7 的优点包括:

  • ✅ 最新、最准确的代码:获取反映最新库版本和最佳实践的建议。
  • ✅ 减少调试时间:减少因过时的 AI 知识导致的错误修复时间。
  • ✅ 拒绝代码幻觉:依赖于已记录的、存在的函数。
  • ✅ 精准版本:能根据你用的特定库版本给答案。
  • ✅ 无缝的工作流程:直接集成到你现有的 AI 编程助手中(如 Cursor、带有 MCP 扩展的 VS Code 等),无需频繁切换到文档网站。

先试试直接让 AI 乱写代码

口说无凭,我们来实际对比下使用 Context7 前后的效果。首先,我们测试一下在没有 Context7 的情况下,AI 是否能够写出 Bug free 的代码。需求非常简单:使用 elasticsearch-rs 库,通过编写 Rust 代码与 Elasticsearch 进行交互,先创建一个索引,然后写入几条文档。

AI 接到指令以后,就开始洋洋洒洒地生成代码了,不到 1 分钟就已经写完了。

但是吧。。。 生成的代码显然无法正常运行,甚至连编译都通过不了,因为肉眼可见就已经能看到有 4 个报错的红线。。。

使用 cargo run 运行程序后,报错信息也清楚地显示出来,主要问题是调用函数时传入的参数类型不正确。

error[E0308]: mismatched types
    --> src/main.rs:133:44
     |
133  |         .refresh(IndicesCreateParts::Index(&[index_name]))
     |                  ------------------------- ^^^^^^^^^^^^^ expected `&str`, found `&[&str; 1]`
     |                  |
     |                  arguments to this enum variant are incorrect
     |
     = note: expected reference `&str`
                found reference `&[&str; 1]`
note: tuple variant defined here
    --> /Users/seven/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/elasticsearch-8.5.0-alpha.1/src/indices.rs:1022:5
     |
1022 |     Index(&'b str),
     |     ^^^^^

error[E0308]: mismatched types
    --> src/main.rs:133:18
     |
133  |         .refresh(IndicesCreateParts::Index(&[index_name]))
     |          ------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `IndicesRefreshParts<'_>`, found `IndicesCreateParts<'_>`
     |          |
     |          arguments to this method are incorrect
     |
note: method defined here
    --> /Users/seven/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/elasticsearch-8.5.0-alpha.1/src/indices.rs:9654:12
     |
9654 |     pub fn refresh<'b>(&'a self, parts: IndicesRefreshParts<'b>) -> IndicesRefresh<'a, 'b, ()> {
   
     |            ^^^^^^^

error[E0308]: mismatched types
   --> src/main.rs:48:51
    |
48  |     let conn_pool = SingleNodeConnectionPool::new(addr);
    |                     ----------------------------- ^^^^ expected `Url`, found `SocketAddr`
    |                     |
    |                     arguments to this function are incorrect
    |
AI 代码解读

安装 Context7 MCP Server

接下来,让我们试试使用 Context7,看看它是否能提升 LLM 生成的代码质量。关于 Context7 MCP Server 的安装方式,可以参考:https://github.com/upstash/context7

目前,常见的 AI 编程助手(如 Cursor、Windsurf、Augment Code 等)都支持配置 MCP Server。以我使用的 Augment Code 为例,只需要添加 Context7 MCP Server 的安装命令即可。

如果你想使用的库在 Context7 网站中还没有被索引,你可以手动添加。在本文中,我手动添加了 elasticsearch-rs 库。以后如果需要使用该库,就无需再手动添加了。

使用 Context7 提升 AI 代码质量

安装完成后,我们让 AI 编程助手重新尝试完成相同的任务,只不过这次我们让 AI 编程助手在开始之前先使用 Context7 查阅代码文档。提示词如下:

先使用 context7 mcp server 查询 elasticsearch-rs 的代码文档,
然后使用 elasticsearch-rs 编写代码和 Elasticsearch 进行交互,
首先创建一个索引,然后写入几条文档,再查询这几条文档
AI 代码解读

从下图可以看到,Augment Code 首先调用了 Context7 MCP Server,获取了基于 elasticsearch-rs 库整理的提示词,然后根据最新的代码进行编程。

生成的代码如下所示:

use elasticsearch::{
    Elasticsearch,
    indices::IndicesCreateParts,
    SearchParts,
    IndexParts,
    http::transport::Transport,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

#[derive(Debug, Serialize, Deserialize)]
struct Document {
    id: u32,
    title: String,
    content: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Connecting to Elasticsearch...");
    println!("Note: This example requires Elasticsearch to be running on http://localhost:9200");
    println!("If Elasticsearch is not running, you will see connection errors.");

    // Create a client connected to localhost using HTTP
    let transport = Transport::single_node("http://localhost:9200")?;
    let client = Elasticsearch::new(transport);

    // Index name
    let index_name = "test_index";

    // Create an index with mapping
    println!("Creating index '{}'...", index_name);
    let _response = client
        .indices()
        .create(IndicesCreateParts::Index(index_name))
        .body(json!({
            "mappings": {
                "properties": {
                    "id": { "type": "integer" },
                    "title": { "type": "text" },
                    "content": { "type": "text" }
                }
            }
        }))
        .send()
        .await?;

    println!("Index creation successful!");

    // Create some documents
    let documents = vec![
        Document {
            id: 1,
            title: "First document".to_string(),
            content: "This is the content of the first document".to_string(),
        },
        Document {
            id: 2,
            title: "Second document".to_string(),
            content: "This is the content of the second document".to_string(),
        },
        Document {
            id: 3,
            title: "Third document".to_string(),
            content: "This is the content of the third document".to_string(),
        },
    ];

    // Index the documents
    println!("Indexing documents...");
    for doc in &documents {
        // Create document ID
        let doc_id = doc.id.to_string();

        // Index with document ID in the URL path
        let _response = client
            .index(IndexParts::IndexId(index_name, &doc_id))
            .body(doc)
            .send()
            .await?;

        println!("Document indexed with ID: {}", doc.id);
    }

    // Refresh the index to make the documents searchable immediately
    client
        .indices()
        .refresh(elasticsearch::indices::IndicesRefreshParts::Index(&[index_name]))
        .send()
        .await?;

    // Search for documents
    println!("Searching for documents...");
    let search_response = client
        .search(SearchParts::Index(&[index_name]))
        .body(json!({
            "query": {
                "match_all": {}
            }
        }))
        .send()
        .await?;

    // Process the search response
    let search_body = search_response.json::<Value>().await?;
    let hits = search_body["hits"]["hits"].as_array().unwrap();

    println!("Found {} documents:", hits.len());
    for hit in hits {
        println!("ID: {}, Source: {}",
            hit["_id"].as_str().unwrap(),
            hit["_source"]
        );
    }

    // Search for specific content
    println!("\nSearching for documents with 'first' in content...");
    let search_response = client
        .search(SearchParts::Index(&[index_name]))
        .body(json!({
            "query": {
                "match": {
                    "content": "first"
                }
            }
        }))
        .send()
        .await?;

    // Process the search response
    let search_body = search_response.json::<Value>().await?;
    let hits = search_body["hits"]["hits"].as_array().unwrap();

    println!("Found {} documents with 'first' in content:", hits.len());
    for hit in hits {
        println!("ID: {}, Source: {}",
            hit["_id"].as_str().unwrap(),
            hit["_source"]
        );
    }

    println!("Done!");
    Ok(())
}
AI 代码解读

让我们尝试运行代码,可以到成功创建了索引,并写入了文档。借助 Context7,AI 编程助手一次就完成了 Bug free 的代码。

 cargo run              
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.70s
     Running `target/debug/elasticsearch-example`
Connecting to Elasticsearch...
Note: This example requires Elasticsearch to be running on http://localhost:9200
If Elasticsearch is not running, you will see connection errors.
Creating index 'test_index'...
Index creation successful!
Indexing documents...
Document indexed with ID: 1
Document indexed with ID: 2
Document indexed with ID: 3
Searching for documents...
Found 3 documents:
ID: 1, Source: {
   "content":"This is the content of the first document","id":1,"title":"First document"}
ID: 2, Source: {
   "content":"This is the content of the second document","id":2,"title":"Second document"}
ID: 3, Source: {
   "content":"This is the content of the third document","id":3,"title":"Third document"}

Searching for documents with 'first' in content...
Found 1 documents with 'first' in content:
ID: 1, Source: {
   "content":"This is the content of the first document","id":1,"title":"First document"}
Done!
AI 代码解读

总结

本文通过实际案例演示了如何利用 Context7 MCP Server 解决 AI 编程助手中的代码幻觉问题和使用过时 API 的问题。借助 Context7 获取最新、最准确的代码建议,显著提升了 AI 生成的代码质量,从而有效提高了开发效率。

参考资料

备注

本文的相关代码可以在 Github 上找到:https://github.com/cr7258/hands-on-lab/tree/main/ai/mcp/context7/elasticsearch

你可以使用 docker-compose up -d 命令来启动一个单节点的 Elasticsearch 集群。通过 http://localhost:9200 进行访问,没有设置用户名和密码。

欢迎关注

目录
打赏
0
12
10
1
40
分享
相关文章
MCP、A2A、ACP、ANP、.... :AI智能体协议的演进展望
多家机构各自推出的MCP、A2A、ACP、ANP等AI智能体协议将会彼此竞争、互补还是趋同?前景有多种可能
91 3
MCP、A2A、ACP、ANP、.... :AI智能体协议的演进展望
【MCP教程系列】搭建基于 Spring AI 的 SSE 模式 MCP 服务并自定义部署至阿里云百炼
本文详细介绍了如何基于Spring AI搭建支持SSE模式的MCP服务,并成功集成至阿里云百炼大模型平台。通过四个步骤实现从零到Agent的构建,包括项目创建、工具开发、服务测试与部署。文章还提供了具体代码示例和操作截图,帮助读者快速上手。最终,将自定义SSE MCP服务集成到百炼平台,完成智能体应用的创建与测试。适合希望了解SSE实时交互及大模型集成的开发者参考。
通义灵码入职蔚来汽车,AI生成代码30%以上
通义灵码已正式应用于蔚来汽车智能座舱部门,近400名成员使用该工具,AI生成代码占比达30%以上,“天探”项目中甚至高达70%-80%。它通过提升代码开发效率、降低维护成本、智能生成单元测试及问题排查等功能助力研发。蔚来选择通义灵码看重其企业专属版的安全能力和知识管理功能。未来,期望AI编程将研发流程规范化,成为类似自动驾驶的高效指引工具。
36 5
云效 MCP Server:AI 驱动的研发协作新范式
云效MCP Server是阿里云云效平台推出的模型上下文协议(Model Context Protocol)标准化接口系统,作为AI助手与DevOps平台的核心桥梁。通过该协议,AI大模型可无缝集成云效DevOps平台,直接访问和操作包括项目管理、代码仓库、工作项等关键研发资产,实现智能化全生命周期管理。其功能涵盖代码仓库管理、代码评审、项目管理和组织管理等多个方面,支持如创建分支、合并请求、查询工作项等具体操作。用户可通过通义灵码内置的MCP市场安装云效MCP服务,并配置个人访问令牌完成集成。实际场景中,AI助手可自动分析需求、生成代码、创建功能分支并提交合并请求,极大提升研发效率。
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
MCP服务器通过提供资源、工具、提示模板三大能力,推动AI实现多轮交互与实体操作。当前生态包含Manus、OpenManus等项目,阿里等企业积极合作,Cursor等工具已集成MCP市场。本文以贪吃蛇游戏为例,演示MCP Server实现流程:客户端连接服务端获取能力集,AI调用工具(如start_game、get_state)控制游戏,通过多轮交互实现动态操作,展示MCP在本地实践中的核心机制与挑战。
289 43
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
5个开源MCP服务器:扩展AI助手能力,高效处理日常工作
AI大语言模型虽强大,但其原生能力仅限于文本对话,难以直接与外部世界交互。MCP(Model Context Protocol)服务器技术作为桥梁,赋予AI实质性环境交互能力,如浏览网页、分析数据等。本文基于实际经验,精选五种开源MCP服务器实现:Stagehand用于网络内容提取;Jupyter适用于数据分析;Opik提供AI行为监控;GitHub集成代码仓库管理;FastAPI-MCP支持自定义API集成。这些工具免费且可定制,为构建实用AI系统奠定基础。文章还提供了配置指南和应用场景剖析,助读者快速上手。
96 3
5个开源MCP服务器:扩展AI助手能力,高效处理日常工作
【MCP教程系列】在阿里云百炼上用Qwen3+且慢MCP,用AI重新定义资产管理效率
通义千问Qwen3通过MCP协议,在Agent中具备强大的工具调度与复杂任务拆解能力,成为构建复杂AI应用的核心引擎。以“基金助手”为例,集成且慢MCP服务后,可一键调用多源金融数据并动态组合分析工具,实现精准调度。在阿里云百炼平台上,只需4步即可构建一个“金融顾问”智能体:开通且慢MCP服务、新建智能体、添加MCP技能、测试效果。此外,还可增加提示词规范输出内容,完成更复杂的任务。
【MCP教程系列】在阿里云百炼上用Qwen3+且慢MCP,用AI重新定义资产管理效率
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
Paper2Code是由韩国科学技术院与DeepAuto.ai联合开发的多智能体框架,通过规划、分析和代码生成三阶段流程,将机器学习论文自动转化为可执行代码仓库,显著提升科研复现效率。
164 18
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
StarRocks MCP Server 开源发布:为 AI 应用提供强大分析中枢
StarRocks MCP Server 提供通用接口,使大模型如 Claude、OpenAI 等能标准化访问 StarRocks 数据库。开发者无需开发专属插件或复杂接口,模型可直接执行 SQL 查询并探索数据库内容。其基于 MCP(Model Context Protocol)协议,包含工具、资源和提示词三类核心能力,支持实时数据分析、自动化报表生成及复杂查询优化等场景,极大简化数据问答与智能分析应用构建。项目地址:https://github.com/StarRocks/mcp-server-starrocks。
Higress MCP Server 安全再升级:API 认证为 AI 连接保驾护航
Higress MCP Server 新增了 API 认证功能,为 AI 连接提供安全保障。主要更新包括:1) 客户端到 MCP Server 的认证,支持 Key Auth、JWT Auth 和 OAuth2;2) MCP Server 到后端 API 的认证,增强第二阶段的安全性。新增功能如可重用认证方案、工具特定后端认证、透明凭证透传及灵活凭证管理,确保安全集成更多后端服务。通过 openapi-to-mcp 工具简化配置,减少手动工作量。企业版提供更高可用性保障,详情参见文档链接。

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等