MCP 提示触发器Azure Functions(公共预览版)

使用 MCP 提示触发器在 模型上下文协议 (MCP) 服务器中定义提示终结点。 客户端可以使用提示在与语言模型交互时生成结构化消息和说明。 提示由用户控制,这意味着它们从服务器向客户端公开,以便用户可以选择它们以供使用。

有关设置和配置详细信息,请参阅概述

Example

注释

对于 C#,Azure Functions MCP 扩展仅支持 isolated worker model

此代码创建一个终结点来公开代码评审提示:

[Function(nameof(CodeReviewChecklist))]
public string CodeReviewChecklist(
    [McpPromptTrigger(CodeReviewPromptName, Description = CodeReviewPromptDescription)]
        PromptInvocationContext context)
{
    logger.LogInformation("Code review checklist prompt invoked.");

    return """
        You are a senior software engineer performing a code review.
        Use the following checklist to evaluate the code:

        1. **Correctness** — Does the code do what it's supposed to?
        2. **Error Handling** — Are edge cases and failures handled?
        3. **Security** — Are there any vulnerabilities (injection, auth, secrets)?
        4. **Performance** — Are there obvious inefficiencies?
        5. **Readability** — Is the code clear and well-named?
        6. **Tests** — Are there adequate tests for the changes?

        Provide your feedback in a structured format with a severity level
        (critical, warning, suggestion) for each finding.
        """;
}

此代码创建一个终结点,用于公开采用两个参数的汇总提示, topic 以及 audience

[Function(nameof(SummarizeContent))]
public string SummarizeContent(
    [McpPromptTrigger(SummarizePromptName, Description = SummarizePromptDescription)]
        PromptInvocationContext context,
    [McpPromptArgument("topic", "The topic or content to summarize.", isRequired: true)]
        string topic,
    [McpPromptArgument("audience", "Target audience (e.g., 'executive', 'developer', 'beginner').")]
        string? audience)
{
    logger.LogInformation("Summarize prompt invoked for topic: {Topic}", topic);

    var audienceInstruction = audience is not null
        ? $"Tailor the summary for a **{audience}** audience."
        : "Write the summary for a general technical audience.";

    return $"""
        Summarize the following topic concisely and accurately:

        **Topic:** {topic}

        {audienceInstruction}

        Guidelines:
        - Start with a one-sentence overview.
        - Include 3–5 key points as bullet items.
        - End with a brief conclusion or recommendation.
        - Keep the total length under 300 words.
        """;
}

还可以使用Program.cs生成器配置ConfigureMcpPrompt提示的提示参数:

var builder = FunctionsApplication.CreateBuilder(args);

builder.ConfigureFunctionsWebApplication();

builder
    .ConfigureMcpPrompt(SummarizePromptName)
    .WithArgument("topic", "The topic or content to summarize.", required: true)
    .WithArgument("audience", "Target audience (e.g., 'executive', 'developer', 'beginner').");

builder.Build().Run();

有关完整的代码示例,请参阅 GitHub 上的 FunctionsMcpPrompts 示例。

Tip

上面的示例对两者 Program.cs 中“code_review”提示的名称和函数等内容使用文本字符串。 请考虑改用共享常量字符串来保持项目之间的同步。

此代码创建一个终结点,用于公开具有多个参数的代码评审提示(一个必需参数,一个可选):

@FunctionName("CodeReviewPrompt")
public String codeReviewPrompt(
        @McpPromptTrigger(
                name = "code_review",
                description = "Generates a code review prompt for the given code snippet",
                title = "Code Review")
        String context,
        @McpPromptArgument(
                name = "code",
                description = "The code to review",
                isRequired = true)
        String code,
        @McpPromptArgument(
                name = "language",
                description = "The programming language")
        String language,
        final ExecutionContext executionContext) {

    executionContext.getLogger().info("Generating code review prompt");

    String lang = (language != null && !language.isEmpty()) ? language : "unknown";
    String snippet = (code != null && !code.isEmpty()) ? code : "// no code provided";

    return "Please review the following " + lang + " code and suggest improvements:\n\n```"
            + lang + "\n" + snippet + "\n```";
}

此代码创建一个终结点,用于公开包含单个必需参数的汇总提示:

@FunctionName("SummarizePrompt")
public String summarizePrompt(
        @McpPromptTrigger(
                name = "summarize",
                description = "Summarizes the provided text",
                title = "Summarize Text")
        String context,
        @McpPromptArgument(
                name = "text",
                description = "The text to summarize",
                isRequired = true)
        String text,
        final ExecutionContext executionContext) {

    executionContext.getLogger().info("Generating summarize prompt");

    String input = (text != null && !text.isEmpty()) ? text : "No text provided";
    return "Please provide a concise summary of the following text:\n\n" + input;
}

有关完整的代码示例,请参阅 GitHub 上的 PromptExamples.java 示例。

注释

MCP 提示支持需要 azure-functions-java-library 版本 3.3.0 或更高版本和 azure-functions-maven-plugin 1.42.0 或更高版本。 更新为 pom.xml 使用预览扩展捆绑包:

<extensionBundle>
  <id>Microsoft.Azure.Functions.ExtensionBundle.Preview</id>
  <version>[4.41, 5.0.0)</version>
</extensionBundle>

JavaScript 的示例代码当前不可用。 有关使用 Node.js的常规指南,请参阅 TypeScript 示例。

此代码创建一个终结点来公开代码评审提示:

app.mcpPrompt('CodeReviewChecklist', {
    promptName: CodeReviewPromptName,
    description: CodeReviewPromptDescription,
    handler: async (_ctx: PromptInvocationContext, context: InvocationContext) => {
        context.log('Code review checklist prompt invoked.');

        return [
            "You are a senior software engineer performing a code review.",
            'Use the following checklist to evaluate the code:',
            '',
            "1. **Correctness** \u2014 Does the code do what it's supposed to?",
            '2. **Error Handling** \u2014 Are edge cases and failures handled?',
            '3. **Security** \u2014 Are there any vulnerabilities (injection, auth, secrets)?',
            '4. **Performance** \u2014 Are there obvious inefficiencies?',
            '5. **Readability** \u2014 Is the code clear and well-named?',
            '6. **Tests** \u2014 Are there adequate tests for the changes?',
            '',
            'Provide your feedback in a structured format with a severity level',
            '(critical, warning, suggestion) for each finding.',
        ].join('\n');
    },
});

此代码创建一个终结点,以使用参数公开文档生成提示:

app.mcpPrompt('GenerateDocumentation', {
    promptName: GenerateDocsPromptName,
    description: GenerateDocsPromptDescription,
    promptArguments: {
        function_name: promptArg.describe("The function to document.").isRequired(),
        style: promptArg.describe("Documentation style (e.g., 'concise', 'verbose')."),
    },
    handler: async (ctx: PromptInvocationContext, context: InvocationContext) => {
        const functionName = ctx.arguments.function_name ?? '(unknown)';
        const style = ctx.arguments.style ?? 'concise';

        context.log(`Generate docs prompt invoked for function: ${functionName}`);

        return [
            `Generate API documentation for the function named **${functionName}**.`,
            '',
            `Documentation style: **${style}**`,
            '',
            'Include the following sections:',
            '- **Description** \u2014 What the function does.',
            '- **Parameters** \u2014 List each parameter with its type and purpose.',
            '- **Return Value** \u2014 What the function returns.',
            '- **Example Usage** \u2014 A short code example showing how to call it.',
        ].join('\n');
    },
});

有关完整的代码示例,请参阅 GitHub 上的 mcp-prompts 示例。

注释

MCP 提示支持需要预览扩展捆绑包和 @azure/functions 版本 4.14.0 或更高版本。 更新为 host.json 使用预览捆绑包:

"extensionBundle": {
  "id": "Microsoft.Azure.Functions.ExtensionBundle.Preview",
  "version": "[4.41, 5.0.0)"
}

并确保引用package.json"@azure/functions": "^4.14.0"

此代码使用 mcp_prompt_trigger 修饰器创建终结点来公开名为 code_review_checklist

@app.mcp_prompt_trigger(
    arg_name="context",
    prompt_name="code_review_checklist",
    description="Returns a structured code review checklist prompt for evaluating code changes."
)
def code_review_checklist(context: func.PromptInvocationContext) -> str:
    logging.info("Code review checklist prompt invoked.")

    return """You are a senior software engineer performing a code review.
Use the following checklist to evaluate the code:

1. **Correctness** — Does the code do what it's supposed to?
2. **Error Handling** — Are edge cases and failures handled?
3. **Security** — Are there any vulnerabilities (injection, auth, secrets)?
4. **Performance** — Are there obvious inefficiencies?
5. **Readability** — Is the code clear and well-named?
6. **Tests** — Are there adequate tests for the changes?

Provide your feedback in a structured format with a severity level
(critical, warning, suggestion) for each finding."""

此代码创建一个终结点,用于公开提示,其中包含生成 API 文档的参数:

@app.mcp_prompt_trigger(
    arg_name="context",
    prompt_name="generate_documentation",
    prompt_arguments=[
        func.PromptArgument("function_name", "The name of the function to document.", required=False),
        func.PromptArgument("style", "Documentation style: 'concise', 'detailed', or 'tutorial'.", required=False)
    ],
    description="Generates API documentation for a function. Arguments are configured in Program.cs."
)
def generate_documentation(context: func.PromptInvocationContext) -> str:
    function_name = context.arguments.get("function_name", "(unknown)")
    style = context.arguments.get("style", "concise")

    logging.info(f"Generate docs prompt invoked for function: {function_name}")

    return f"""Generate API documentation for the function named **{function_name}**.

Documentation style: **{style}**

Include the following sections:
- **Description** — What the function does.
- **Parameters** — List each parameter with its type and purpose.
- **Return Value** — What the function returns.
- **Example Usage** — A short code example showing how to call it."""

有关完整的代码示例,请参阅 GitHub 上的 FunctionsMcpPrompts 示例。

注释

MCP 提示支持需要预览扩展捆绑包和 azure-functions 版本 2.2.0b2 或更高版本。 更新为 host.json 使用预览捆绑包:

"extensionBundle": {
  "id": "Microsoft.Azure.Functions.ExtensionBundle.Preview",
  "version": "[4.41, 5.0.0)"
}

并确保你的 requirements.txt 包括 azure-functions>=2.2.0b2

Important

MCP 扩展目前不支持 PowerShell 应用。

特性

C# 库用于 McpPromptTriggerAttribute 定义函数触发器。

该特性的构造函数采用以下参数:

参数 Description
PromptName (必需)MCP 触发器终结点公开的提示的名称。

该属性还支持以下命名属性:

财产 Description
标题 (可选)用于在 MCP 客户端接口中显示目的的人类可读标题。
说明 (可选)客户端提示终结点的友好说明。
PromptArguments (可选)提示参数架构的 JSON 序列化字符串表示形式。 还可以使用特性 McpPromptArgument 作为提供参数的替代方法。
Metadata (可选)提示的 JSON 序列化元数据字符串。
图标 (可选)用于在客户端接口中显示的图标定义的 JSON 序列化字符串。

请参阅 “用法 ”,了解如何将提示的参数定义为输入参数。

Annotations

使用 @McpPromptTrigger 批注创建在远程 MCP 服务器中公开提示终结点的函数。

注释支持以下配置选项:

参数 Description
name (必需)绑定参数名称和唯一提示标识符。
说明 (可选)客户端提示终结点的友好说明。
标题 (可选)用于在 MCP 客户端接口中显示目的的人类可读标题。
promptArguments (可选)参数定义的内联 JSON 数组,作为批注的 McpPromptArgument 替代方法。
metadata (可选)提示的 JSON 序列化元数据字符串。
图标 (可选)用于在客户端接口中显示的图标定义的 JSON 序列化字符串。

使用 @McpPromptArgument 批注定义单个提示参数。 用此注释批注注释函数中的每个参数。

@McpPromptArgument 注支持以下配置选项:

参数 Description
name (必需)用作绑定参数名称和 MCP 协议参数标识符的参数名称。
说明 (可选)参数所表示内容的说明。
isRequired (可选)如果设置为 />,则调用提示时需要参数。 默认值为 false.

修饰器

仅适用于 Python v2 编程 model.

支持 mcp_prompt_trigger以下 MCP 提示触发器属性:

财产 Description
arg_name 函数代码中用于访问提示调用上下文的变量名称(通常 context)。
prompt_name (必需)函数终结点公开的 MCP 服务器提示的名称。
说明 函数终结点公开的 MCP 服务器提示的说明。
标题 在 MCP 客户端接口中用于显示目的的可选标题。
prompt_arguments 定义提示接受来自客户端的参数的对象列表 PromptArgument

Configuration

在代码中定义触发器的绑定选项。 下表描述了每个选项:

Option Description
type 设置为 mcpPromptTrigger。 仅用于泛型定义。
promptName (必需)函数终结点公开的 MCP 服务器提示的名称。
说明 函数终结点公开的 MCP 服务器提示的说明。
promptArguments 使用帮助程序定义提示参数 promptArg 的对象。 每个键都是参数名称,值描述和配置参数。
处理器 包含实际函数代码的方法。

有关完整示例,请参阅 “示例”部分

Usage

MCP 提示触发器可以绑定到以下类型:

类型 Description
PromptInvocationContext 表示提示调用的对象,包括提示名称、参数、会话 ID 和传输信息。

PromptInvocationContext 类型提供以下属性:

财产 类型 Description
名称 string 正在调用的提示的名称。
参数 Dictionary<string, string>? 为提示调用提供的参数。
SessionId string? 与当前提示调用关联的会话 ID。
运输 Transport? 当前调用的传输信息。

@McpPromptTrigger 注绑定到一个 String 参数,该参数包含提示调用上下文作为 JSON 字符串。 触发器函数通过带注释 @McpPromptArgument的参数接收参数值。

提示处理程序函数具有两个参数:

参数 类型 Description
环 磷 酰 胺 PromptInvocationContext 提示调用上下文,其中包括提示nameargumentssessionIdtransport信息。
context InvocationContext Azure Functions调用上下文,该上下文提供日志记录和其他运行时信息。

提示参数

MCP 客户端使用参数调用提示,以提供用于生成提示消息的数据和上下文。 客户端知道如何根据提示作为协议的一部分播发的参数定义收集和传递这些参数。 在函数代码中为提示定义参数。

定义提示参数时,默认将其设置为可选。 客户端在调用提示时可以省略它。 如果提示在没有提示的情况下无法运行参数,则显式将参数标记为必需。

在 C# 中,可以通过多种方式为提示定义参数。 使用哪种方法是代码样式首选项。 选项包括:

  • 函数使用 McpPromptArgument 特性获取输入参数。
  • 可以使用该文件 FunctionsApplicationBuilderProgram.cs 定义参数。

通过将属性应用于 McpPromptArgument 函数中的输入绑定样式参数来定义一个或多个提示参数。

McpPromptArgumentAttribute 类型支持以下属性:

财产 Description
ArgumentName 向客户端公开的提示参数的名称。
说明 参数所表示的内容的说明。
是必需的 (可选)如果设置为 />,则调用提示时,需要提示参数。 默认值为 false.

可以在CodeReviewPrompt查看这些属性。

可以在触发器定义的 prompt_arguments 字段中配置提示参数,该字段是对象列表 PromptArgument

构造 PromptArgument 为:

func.PromptArgument("argument_name", "Description of the argument", required=True)

字段 PromptArgument 包括:

财产 Description
name 向客户端公开的提示参数的名称。
说明 参数所表示的内容的说明。
required (可选)如果设置为 />,则调用提示时需要参数。 默认值为 False.

在Java中,通过使用单个函数参数的 @McpPromptArgument 注释来定义提示参数。 用此批注批注批注表示提示参数的每个参数。 指定参数名称、说明以及是否需要参数。

可以看到 示例中使用的这些批注。

  promptArguments: {
    code: promptArg.describe("The code to review").isRequired(),
    language: promptArg.describe("The programming language"),
  }

返回类型

MCP 提示触发器支持以下返回类型:

类型 Description
string 作为 MCP GetPromptResult中的单个用户角色短信返回。

MCP 提示触发器支持以下返回类型:

类型 Description
String 作为 MCP GetPromptResult中的单个用户角色短信返回。

MCP 提示触发器支持以下返回类型:

类型 Description
str 作为 MCP GetPromptResult中的单个用户角色短信返回。

该函数应返回 string 包含提示消息文本的函数。 字符串包装为 MCP GetPromptResult中的单个用户角色文本消息。

提示发现

函数应用启动时,它会向 MCP 服务器注册所有提示触发器函数。 客户端通过调用 MCP prompts/list 方法发现可用的提示。 此方法返回每个提示的名称、标题、说明、参数、图标和元数据(通过 meta 字段)。 客户端使用提示名称和参数调用提示来调用 prompts/get 提示。

Sessions

用于 SessionId 标识发出请求的 MCP 会话的属性 PromptInvocationContext 。 使用此属性在生成提示时维护每会话状态或应用特定于会话的逻辑。

host.json 设置

host.json 文件包含控制 MCP 触发器行为的设置。 有关可用设置的详细信息,请参阅 host.json 设置部分。

适用于 Azure FunctionsMCP 工具触发器>
Azure FunctionsMCP 资源触发器>