MCP prompt trigger for Azure Functions (public preview)

使用 MCP 提示觸發器在 模型情境協定(MCP) 伺服器中定義提示端點。 用戶端在與語言模型互動時,可以使用提示產生結構化訊息與指令。 提示由使用者控制,意即它們會從伺服器暴露給用戶端,讓使用者選擇使用。

關於設置與設定細節,請參閱 overview。

Example

目前這款綁定沒有 Go 支援。

Note

對於 C#,Azure Functions MCP 擴充只支援 孤立工作者模型。

此程式碼建立一個端點以暴露程式碼審查提示:

[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.
        """;
}

此程式碼建立一個端點,以暴露一個包含兩個參數 和 topicaudience的摘要提示:

[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

上述範例使用字串來表示像是「code_review」提示詞名稱和函式。Program.cs 請考慮改用共用常數字串,讓專案中的內容保持同步。

此程式碼建立一個端點,以暴露包含多個參數(一個必要,一個可選)的程式碼審查提示詞:

@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範例。

Note

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');
    },
});

完整程式碼範例請參見 mcp-prompts 範例,請參考 GitHub。

Note

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範例。

Note

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
提示名稱 (必修)MCP 觸發端點所暴露的提示詞名稱。

該屬性也支援以下具命名的屬性:

房產 Description
標題 (可選)一個用於 MCP 用戶端介面顯示目的的人類可讀標題。
Description (可選)為客戶提供對提示端點的友善描述。
PromptArguments (可選)一個以 JSON 序列化的字串表示,代表提示參數結構。 你也可以用這個 McpPromptArgument 屬性作為提供參數的替代方式。
Metadata (可選)一個 JSON 序列化的元資料字串用於提示詞。
圖示 (可選)一個以 JSON 序列化的圖示定義字串,用於用戶端介面顯示。

請參閱 使用法 ,學習如何定義提示詞的參數作為輸入參數。

Annotations

利用註 @McpPromptTrigger 解建立一個函式,在遠端 MCP 伺服器中暴露一個提示端點。

註解支援下列組態選項:

參數 Description
name (必修)綁定參數名稱與唯一提示詞識別碼。
描述 (可選)為客戶提供對提示端點的友善描述。
標題 (可選)一個用於 MCP 用戶端介面顯示目的的人類可讀標題。
promptArguments (可選)一個內嵌的 JSON 參數陣列,作為註 McpPromptArgument 解的替代方案。
元資料 (可選)一個 JSON 序列化的元資料字串用於提示詞。
圖示 (可選)一個以 JSON 序列化的圖示定義字串,用於用戶端介面顯示。

使用 @McpPromptArgument 註解來定義個別提示論證。 用這個註解標註你函式中的每個參數。

@McpPromptArgument註解支援下列組態選項:

參數 Description
name (必修)參數名稱同時用作綁定參數名稱及 MCP 協定參數識別碼。
描述 (可選)說明這個論點所代表的意義。
是必填 (可選)若設為 true,則在呼叫提示時必須使用該參數。 預設為 false。

裝飾項目

僅適用於 Python v2 程式設計模型。

以下 MCP 提示觸發條件支援於 mcp_prompt_trigger:

房產 Description
arg_name 變數名稱(通常 context)在函式程式碼中用於存取提示詞調用上下文。
prompt_name (必修)函式端點所暴露的 MCP 伺服器提示字元名稱。
描述 函式端點所暴露的 MCP 伺服器提示字元描述。
標題 MCP 用戶端介面中顯示用途的選用標題。
prompt_arguments 一串 PromptArgument 定義提示從客戶端接受參數的物件清單。

設定

在程式碼中定義觸發器的綁定選項。 下表說明每個選項:

Option Description
type 設定為 mcpPromptTrigger。 只能用通用定義使用。
提示名稱 (必修)函式端點所暴露的 MCP 伺服器提示字元名稱。
描述 函式端點所暴露的 MCP 伺服器提示字元描述。
promptArguments 一個用輔助工具定義提示論題 promptArg 的物件。 每個鍵是參數名稱,值則描述並配置參數。
處理程式 包含實際函式程式碼的方法。

完整範例請參見 範例章節。

Usage

MCP 提示觸發器可綁定以下類型:

類型 Description
PromptInvocationContext 一個代表提示喚用的物件,包括提示詞名稱、參數、會話 ID 及傳輸資訊。

該 PromptInvocationContext 類型提供以下特性:

房產 類型 Description
Name string 被喚起的提示名稱。
引數 Dictionary<string, string>? 這些論證提供了即時召喚的基礎。
SessionId string? 與當前提示詞呼叫相關的會話 ID。
交通 Transport? 目前召喚的傳輸資訊。

註 @McpPromptTrigger 解綁定到 String 包含提示調用上下文的參數,作為 JSON 字串。 觸發函數透過標 @McpPromptArgument註 的參數接收參數值。

提示處理程式有兩個參數:

參數 類型 Description
CTX PromptInvocationContext 提示詞調用上下文,包含提示詞 name、 arguments、 、 sessionId及 transport 資訊。
背景 InvocationContext Azure Functions 調用上下文,提供日誌及其他執行時資訊。

即時論證

MCP 用戶端會呼叫帶有參數的提示,以提供資料與上下文以產生提示訊息。 用戶端知道如何根據提示中宣稱的參數定義來收集並傳遞這些參數。 你在函式程式碼中定義提示詞的參數。

當你定義提示參數時,預設它是可選的。 客戶端在呼叫提示時可以省略它。 如果提示詞無法在參數下運作,則明確標記為必要。

在 C# 中,你可以用多種方式定義提示詞的參數。 您使用哪種方法取決於程式碼樣式偏好。 選項包括:

  • 你的函式會用屬性來取得輸入參數 McpPromptArgument 。
  • 你用 來 FunctionsApplicationBuilder 定義檔案中的 Program.cs 參數。

透過將屬性套用 McpPromptArgument 到函式中的輸入綁定式參數,定義一個或多個提示參數。

此 McpPromptArgumentAttribute 類型支援下列屬性:

房產 Description
論點名稱 會被客戶接觸到的提示論點名稱。
Description 說明論點所代表的意義。
是必要 (可選)若設為 true,則在呼叫提示時必須使用提示詞參數。 預設為 false。

你可以在CodeReviewPrompt中看到這些屬性的使用。

你可以在觸發定義欄位 prompt_arguments 中設定提示參數,該欄位是物件清單 PromptArgument 。

A PromptArgument 可構造為:

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

a PromptArgument 的域為:

房產 Description
name 你向客戶展示的提示論點名稱。
描述 說明論點所代表的意義。
required (可選)若設為 True,則在呼叫提示時必須使用該參數。 預設為 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中。

函式應回傳包含提示訊息文字的 a string 。 該字串在 MCP GetPromptResult中以單一使用者角色文字訊息包裝。

即時發現

當函式應用程式啟動時,會向 MCP 伺服器註冊所有提示觸發函式。 用戶端透過呼叫 MCP prompts/list 方法來發現可用提示。 此方法會回傳每個提示的名稱、標題、描述、參數、圖示及元資料(透過欄位 meta )。 客戶透過撥打 prompts/get 提示名稱和參數來呼叫提示。

會議

SessionId屬性 on PromptInvocationContext 識別發出請求的 MCP 會話。 使用此屬性來維持每個會話狀態,或在產生提示時套用會話特定的邏輯。

host.json 設定

host.json 檔案包含控制MCP觸發行為的設定。 請參閱 host.json settings 章節了解可用設定的詳細資訊。

MCP 工具觸發器用於 Azure Functions
MCP 資源觸發器用於 Azure Functions