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
    |

安装 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 进行交互,
首先创建一个索引,然后写入几条文档,再查询这几条文档

从下图可以看到,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(())
}

让我们尝试运行代码,可以到成功创建了索引,并写入了文档。借助 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!

总结

本文通过实际案例演示了如何利用 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 进行访问,没有设置用户名和密码。

欢迎关注

目录
相关文章
|
10天前
|
人工智能 Java Serverless
【MCP教程系列】搭建基于 Spring AI 的 SSE 模式 MCP 服务并自定义部署至阿里云百炼
本文详细介绍了如何基于Spring AI搭建支持SSE模式的MCP服务,并成功集成至阿里云百炼大模型平台。通过四个步骤实现从零到Agent的构建,包括项目创建、工具开发、服务测试与部署。文章还提供了具体代码示例和操作截图,帮助读者快速上手。最终,将自定义SSE MCP服务集成到百炼平台,完成智能体应用的创建与测试。适合希望了解SSE实时交互及大模型集成的开发者参考。
|
10天前
|
人工智能 JavaScript Devops
云效 MCP Server:AI 驱动的研发协作新范式
云效MCP Server是阿里云云效平台推出的模型上下文协议(Model Context Protocol)标准化接口系统,作为AI助手与DevOps平台的核心桥梁。通过该协议,AI大模型可无缝集成云效DevOps平台,直接访问和操作包括项目管理、代码仓库、工作项等关键研发资产,实现智能化全生命周期管理。其功能涵盖代码仓库管理、代码评审、项目管理和组织管理等多个方面,支持如创建分支、合并请求、查询工作项等具体操作。用户可通过通义灵码内置的MCP市场安装云效MCP服务,并配置个人访问令牌完成集成。实际场景中,AI助手可自动分析需求、生成代码、创建功能分支并提交合并请求,极大提升研发效率。
|
10天前
|
人工智能 监控 JavaScript
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
MCP服务器通过提供资源、工具、提示模板三大能力,推动AI实现多轮交互与实体操作。当前生态包含Manus、OpenManus等项目,阿里等企业积极合作,Cursor等工具已集成MCP市场。本文以贪吃蛇游戏为例,演示MCP Server实现流程:客户端连接服务端获取能力集,AI调用工具(如start_game、get_state)控制游戏,通过多轮交互实现动态操作,展示MCP在本地实践中的核心机制与挑战。
236 43
MCP实战之Agent自主决策-让 AI玩转贪吃蛇
|
17天前
|
机器学习/深度学习 人工智能 JSON
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
Paper2Code是由韩国科学技术院与DeepAuto.ai联合开发的多智能体框架,通过规划、分析和代码生成三阶段流程,将机器学习论文自动转化为可执行代码仓库,显著提升科研复现效率。
151 18
这个AI把arXiv变成代码工厂,快速复现顶会算法!Paper2Code:AI论文自动转代码神器,多智能体框架颠覆科研复现
|
22天前
|
人工智能 自然语言处理 监控
LongPort MCP:证券业首个券商MCP,AI赋能智能投资新时代,散户也能玩转机构级交易
LongPort MCP是长桥集团推出的证券行业首个券商模型上下文协议,通过标准化接口实现AI与金融服务的无缝对接,支持自然语言交互的智能投资服务。
248 8
LongPort MCP:证券业首个券商MCP,AI赋能智能投资新时代,散户也能玩转机构级交易
|
18天前
|
人工智能 搜索推荐 API
RAG vs. MCP: 你不知道你需要的 AI 充电接口
本文通过“充电接口”比喻,对比了两种AI技术:RAG(特定充电口)和MCP(通用充电口)。RAG像专用数据线,每次需连接外部数据库检索信息,适合动态查询;MCP则似USB-C,依靠内置记忆提供快速、个性化响应,适用于长期交互。两者各有优劣,RAG灵活但效率低,MCP高效却可能缺乏最新数据。未来可能是两者的结合:MCP负责上下文记忆,RAG获取最新资讯,实现更自然的AI对话体验。文章还探讨了如何用Apipost设计适配两者的API,助力AI系统开发。
|
24天前
|
人工智能 Java 定位技术
Java 开发玩转 MCP:从 Claude 自动化到 Spring AI Alibaba 生态整合
本文详细讲解了Java开发者如何基于Spring AI Alibaba框架玩转MCP(Model Context Protocol),涵盖基础概念、快速体验、服务发布与调用等内容。重点包括将Spring应用发布为MCP Server(支持stdio与SSE模式)、开发MCP Client调用服务,以及在Spring AI Alibaba的OpenManus中使用MCP增强工具能力。通过实际示例,如天气查询与百度地图路线规划,展示了MCP在AI应用中的强大作用。最后总结了MCP对AI开发的意义及其在Spring AI中的实现价值。
436 9
|
23天前
|
人工智能 自然语言处理 JavaScript
我定制的通义灵码 Project Rules,用 AI 写出“更懂我”的代码
本文分享了一名全栈开发同学使用通义灵码做代码生成、接口注释、测试代码补全等工作,效率明显提升的体会。
|
24天前
|
人工智能 自然语言处理 JavaScript
我定制的通义灵码 Project Rules,用 AI 写出“更懂我”的代码
本文分享了一名全栈开发者使用通义灵码的经验,重点介绍了其新推出的“Project Rules”功能。通过定制规则,解决了团队代码风格不统一、AI生成代码不符合项目规范等问题。示例配置包括Vue 3 + Composition API的语法规范、命名约定、注释风格等。作者总结,该功能显著提升了编码效率和团队协作一致性,并建议用户根据自身需求定制规则以优化体验。文中还提出了对团队规则共享、行业模版内置等功能的期待。
|
9天前
|
人工智能 数据挖掘 大数据
“龟速”到“光速”?算力如何加速 AI 应用进入“快车道”
阿里云将联合英特尔、蚂蚁数字科技专家,带来“云端进化论”特别直播。
49 11