MCP resource trigger for Azure Functions

使用 MCP 資源觸發器來定義模型 上下文協定(MCP) 伺服器中的資源端點。 用戶端可利用資源存取上下文資訊,如檔案內容、資料庫架構或 API 文件。

如需安裝和組態詳細數據的詳細資訊,請參閱概 觀。

如需完整的端對端 MCP 資源觸發器範例,請參見 使用 Azure Functions 建構 MCP 應用程式。

Example

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

備註

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

這個第一個範例展示了如何利用資源實作 MCP 應用程式的 UI 元素。

以下程式碼建立一個端點,以暴露一個名為 Weather Widget 資源的資源,該資源以整合的 HTML 內容提供互動式天氣顯示。 該資源用這個 ui:// 方案來表示它是 MCP 應用程式介面資源。

// Optional resource metadata
private const string ResourceMetadata = """
    {
        "ui": {
            "prefersBorder": true
        }
    }
    """;

[Function(nameof(GetWeatherWidget))]
public string GetWeatherWidget(
    [McpResourceTrigger(
        "ui://weather/index.html",
        "Weather Widget",
        MimeType = "text/html;profile=mcp-app",
        Description = "Interactive weather display for MCP Apps")]
    [McpMetadata(ResourceMetadata)]
        ResourceInvocationContext context)
{
    var file = Path.Combine(AppContext.BaseDirectory, "app", "dist", "index.html");
    return File.ReadAllText(file);
}

工具可以透過在元資料中宣告 a resourceUri 並指向 ui://weather/index.html來參考此資源。 當工具被呼叫時,MCP 主機會擷取資源並渲染:

private const string ToolMetadata = """
    {
        "ui": {
            "resourceUri": "ui://weather/index.html"
        }
    }
    """;

[Function(nameof(GetWeather))]
public async Task<object> GetWeather(
    [McpToolTrigger(nameof(GetWeather), "Returns current weather for a location via Open-Meteo.")]
    [McpMetadata(ToolMetadata)]
        ToolInvocationContext context,
    [McpToolProperty("location", "City name to check weather for (e.g., Seattle, New York, Miami)")]
        string location)
{
    var result = await _weatherService.GetCurrentWeatherAsync(location);
    return result;
}

完整程式碼範例請參見 WeatherFunction.cs。

這個程式碼範例建立一個端點,用來暴露一個名為 readme 資源的資源,該資源會讀取 markdown 檔案並以明文回傳其內容。 用戶端可透過 file://readme.md URI 存取此資源。

    private const string ReadmeMetadata = """
        {
            "author": "John Doe",
            "file": {
                "version": 1.0,
                "releaseDate": "2024-01-01"
            },
            "test": {
                "example": ["list", "of", "values"]
            }
        }
        """;

    [Function(nameof(GetTextResource))]
    public string GetTextResource(
        [McpResourceTrigger(
            "file://readme.md",
            "readme",
            Description = "Application readme file",
            MimeType = "text/plain")]
        [McpMetadata(ReadmeMetadata)]
        ResourceInvocationContext context)
    {
        _logger.LogInformation("Reading text resource from local file storage");
        var file = Path.Combine(AppContext.BaseDirectory, "assets", "readme.md");
        return File.ReadAllText(file);
    }

在此範例中,一個名為 assets 包含 的 readme 資料夾在建置時與函式應用程式一同被捆綁,因為檔案中 .csproj 包含以下指令:

<ItemGroup>
  <None Update="assets\**\*">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

完整程式碼範例請參見 Azure Functions MCP 擴充套件。

目前無法使用 JavaScript 的範例程式代碼。 參考 TypeScript 範例以獲得一般指引。

以下程式碼註冊了一個名為 Weather Widget 資源的資源,該資源作為打包的 HTML 內容,提供互動式天氣顯示。 該資源用這個 ui:// 方案來表示它是 MCP 應用程式介面資源。

// Constants for the Weather Widget resource
const WEATHER_WIDGET_URI = "ui://weather/index.html";
const WEATHER_WIDGET_NAME = "Weather Widget";
const WEATHER_WIDGET_DESCRIPTION = "Interactive weather display for MCP Apps";
const WEATHER_WIDGET_MIME_TYPE = "text/html;profile=mcp-app";

// Metadata for the resource 
const RESOURCE_METADATA = JSON.stringify({
  ui: {
    prefersBorder: true
  }
});

app.mcpResource("getWeatherWidget", {
  uri: WEATHER_WIDGET_URI,
  resourceName: WEATHER_WIDGET_NAME,
  description: WEATHER_WIDGET_DESCRIPTION,
  mimeType: WEATHER_WIDGET_MIME_TYPE,
  metadata: RESOURCE_METADATA,
  handler: getWeatherWidget,
});

以下程式碼為處理器:getWeatherWidget

export async function getWeatherWidget(
  resourceContext: unknown,
  context: InvocationContext
): Promise<string> {
  context.log("Getting weather widget");

  try {
    const filePath = path.join(__dirname, "..", "..", "..", "src", "app", "dist", "index.html");
    return fs.readFileSync(filePath, "utf-8");
  } catch (error) {
    context.log(`Error reading weather widget file: ${error}`);
    return `<!DOCTYPE html>
      <html>
      <head><title>Weather Widget</title></head>
      <body>
      <h1>Weather Widget</h1>
      <p>Widget content not found. Please ensure the app/dist/index.html file exists.</p>
      </body>
      </html>`;
  }
}

工具可以透過在元資料中宣告 a resourceUri 來參考此資源。 當工具被呼叫時,MCP 主機會擷取資源並渲染:

// Metadata for the tool (as valid JSON string)
const TOOL_METADATA = JSON.stringify({
  ui: {
    resourceUri: "ui://weather/index.html"
  }
});

app.mcpTool("getWeather", {
  toolName: "GetWeather",
  description: "Returns current weather for a location via Open-Meteo.",
  toolProperties: {
    location: arg.string().describe("City name to check weather for (e.g., Seattle, New York, Miami)")
  },
  metadata: TOOL_METADATA,
  handler: getWeather,
});

完整程式碼範例請參見 weatherMcpApp.ts。

這很重要

TypeScript 的 MCP 資源觸發器需要套件的版本 4.12.0 或更新 @azure/functions 版本。

以下程式碼註冊一個名為 Weather Widget 資源的資源,該資源作為整合的 HTML 內容提供互動式天氣顯示。 該資源用這個 ui:// 方案來表示它是 MCP 應用程式介面資源。

# Constants for the Weather Widget resource
WEATHER_WIDGET_URI = "ui://weather/index.html"
WEATHER_WIDGET_NAME = "Weather Widget"
WEATHER_WIDGET_DESCRIPTION = "Interactive weather display for MCP Apps"
WEATHER_WIDGET_MIME_TYPE = "text/html;profile=mcp-app"

# Metadata for the resource 
RESOURCE_METADATA = '{"ui": {"prefersBorder": true}}'

@app.mcp_resource_trigger(
    arg_name="context",
    uri=WEATHER_WIDGET_URI,
    resource_name=WEATHER_WIDGET_NAME,
    description=WEATHER_WIDGET_DESCRIPTION,
    mime_type=WEATHER_WIDGET_MIME_TYPE,
    metadata=RESOURCE_METADATA
)
def get_weather_widget(context) -> str:
    """Get the weather widget HTML content."""
    logging.info("Getting weather widget")

    current_dir = Path(__file__).parent
    file_path = current_dir / "app" / "dist" / "index.html"

    if file_path.exists():
        return file_path.read_text(encoding="utf-8")
    else:
        logging.warning(f"Weather widget file not found at: {file_path}")
        return """<!DOCTYPE html>
        <html>
        <head><title>Weather Widget</title></head>
        <body>
        <h1>Weather Widget</h1>
        <p>Widget content not found. Please ensure the app/index.html file exists.</p>
        </body>
        </html>"""

工具可以透過在元資料中宣告 a resourceUri 並指向 ui://weather/index.html來參考此資源。 當工具被呼叫時,MCP 主機會擷取資源並渲染:

# Metadata for the tool
TOOL_METADATA = '{"ui": {"resourceUri": "ui://weather/index.html"}}'

@app.mcp_tool(metadata=TOOL_METADATA)
@app.mcp_tool_property(arg_name="location", description="City name to check weather for (e.g., Seattle, New York, Miami)")
def get_weather(location: str) -> Dict[str, Any]:
    """Returns current weather for a location via Open-Meteo."""
    logging.info(f"Getting weather for location: {location}")

    result = weather_service.get_current_weather(location)
    return json.dumps(result)

完整程式碼範例請參見 function_app.py。

備註

Python 的 MCP 資源觸發器需要 套件的版本為 或更新版本,並使用 Python 3.13。

以下程式碼註冊一個名為 Weather Widget 資源的資源,該資源作為整合的 HTML 內容提供互動式天氣顯示。 該資源用這個 ui:// 方案來表示它是 MCP 應用程式介面資源。

private static final String RESOURCE_METADATA = """
        {
            "ui": {
                "prefersBorder": true
            }
        }
        """;

@FunctionName("GetWeatherWidget")
public String getWeatherWidget(
        @McpResourceTrigger(
                name = "context",
                uri = "ui://weather/index.html",
                resourceName = "Weather Widget",
                title = "Weather Widget",
                description = "Interactive weather display for MCP Apps",
                mimeType = "text/html;profile=mcp-app")
        @McpMetadata(
                name = "context",
                json = RESOURCE_METADATA)
        String context,
        final ExecutionContext executionContext) {

    executionContext.getLogger().info("GetWeatherWidget: serving weather widget UI");

    // Load the bundled HTML file from the CWD-relative path
    java.io.File file = new java.io.File("app/dist/index.html");
    if (file.exists()) {
        return java.nio.file.Files.readString(file.toPath(), StandardCharsets.UTF_8);
    }

    return "<html><body><p>Weather widget UI not found.</p></body></html>";
}

工具可以透過在元資料中宣告 a resourceUri 並指向 ui://weather/index.html來參考此資源。 當工具被呼叫時,MCP 主機會擷取資源並渲染:

private static final String TOOL_METADATA = """
        {
            "ui": {
                "resourceUri": "ui://weather/index.html"
            }
        }
        """;

@FunctionName("GetWeather")
public String getWeather(
        @McpToolTrigger(
                name = "GetWeather",
                description = "Returns current weather for a location via Open-Meteo.")
        @McpMetadata(
                name = "GetWeather",
                json = TOOL_METADATA)
        String context,
        @McpToolProperty(
                name = "location",
                propertyType = "string",
                description = "City name to check weather for (e.g., Seattle, New York, Miami)")
        String location,
        final ExecutionContext executionContext) {

    executionContext.getLogger().info("GetWeather: looking up weather for '" + location + "'");

    Object result = weatherService.getCurrentWeather(location);

    return MAPPER.writeValueAsString(result);
}

完整程式碼範例請參見 WeatherFunction.java。

這很重要

MCP 延伸模組目前不支援PowerShell應用程式。

屬性

C# 連結庫會使用 McpResourceTriggerAttribute 來定義函式觸發程式。

屬性的建構函式會採用下列參數:

參數 Description
URI (必修)資源的 URI,定義資源的位址。 例如, ui://weather/index.html 定義了一個靜態資源 URI。
ResourceName (必修)MCP 資源觸發端點所暴露的資源名稱。

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

房產 Description
說明 (可選)為客戶提供一份友善的資源端點描述。
標題 (可選)一個用於 MCP 用戶端介面顯示目的的人類可讀標題。
MimeType (可選)資源回傳內容的 MIME 類型。 例如, text/html;profile=mcp-app MCP 應用程式的 UI 資源、 text/plain 純文字或 application/json JSON 資料。
大小 (可選)資源內容的大小(以位元組為單位)。
中繼資料 (可選)一個資源的 JSON 序列化元資料字串。 你也可以用屬性 McpMetadata 作為提供元資料的替代方式。

你可以用這個 [McpMetadata] 屬性來提供更多資源的元資料。 當用戶端呼叫 resources/list時,這些元資料會包含在每個資源的元欄位中,並會影響資源內容的顯示或處理方式。

請參閱 使用情況, 了解資源觸發如何為你的函式提供資料。

裝飾項目

以下 MCP 資源觸發屬性支援於 mcp_resource_trigger:

房產 Description
arg_name 變數名稱(通常 context)在函式程式碼中使用,用以存取觸發有效載荷。
uri (必修)資源的唯一 URI 識別碼。 一定是徹底的上呼吸道感染。
resource_name (必修)資源的可讀名稱。
標題 MCP 用戶端介面中顯示用途的選用標題。
描述 函式端點所暴露的 MCP 資源描述。
mime_type 資源回傳內容的 MIME 類型。 例如, text/html;profile=mcp-app 對於 MCP 應用程式的 UI 資源,以及 text/plain 純文字。
大小 資源內容的預期大小(以位元組為單位)表示(若已知)。
metadata 一個 JSON 序列化的額外元資料字串。

備註

裝飾器僅在 Python v2 程式設計模型中提供。

設定

在程式碼中定義觸發器的綁定選項。 扳機支援以下選項:

選項 Description
type 設定為 mcpResourceTrigger。 只能用通用定義使用。
uri (必修)函式端點所暴露的 MCP 資源的 URI。 一定是徹底的上呼吸道感染。
resourceName (必修)函式端點所暴露的 MCP 資源的人類可讀名稱。
標題 MCP 用戶端介面中顯示用途的選用標題。
描述 函式端點所暴露的 MCP 資源描述。
MIME類型 資源回傳內容的 MIME 類型。 例如: text/html;profile=mcp-app 。
大小 資源內容的預期大小(以位元組為單位)表示(若已知)。
metadata 一個 JSON 序列化的額外元資料字串。
處理程式 包含實際函式程式碼的方法。

屬性

將註解套用 @McpResourceTrigger 到函式參數以定義 MCP 資源觸發器。

註 @McpResourceTrigger 解支持以下特性:

房產 Description
name 必須的。 資源調用上下文參數的綁定名稱。
uri 必須的。 MCP 資源的 URI(例如 "file://readme.md" ,或 "ui://weather/index.html")。
resourceName 必須的。 MCP 資源的顯示名稱。
title 選擇性。 一個人類可讀的標題,方便展示。 與 為程式識別碼不同 resourceName,這是介面呈現的友善標籤。
description 選擇性。 這是一份對此資源的易讀描述。
mimeType 選擇性。 資源內容的 MIME 類型(例如 "text/plain", , "text/html", "image/png", )。 "text/html;profile=mcp-app"
size 選擇性。 以位元組為單位的資源大小。 預設為 -1 (未指定)。
dataType 選擇性。 定義函式執行時應該如何處理參數值。 可能的值: "" (預設,反序列化為參數型別)、 "string", "binary"。

元資料註解

你可以選擇用同一個參數@McpMetadata套用@McpResourceTrigger,將任意的 JSON 元資料附加到資源上。 當用戶端呼叫 _meta時,這些元資料會顯示在 MCP 協定欄位resources/list中。

註 @McpMetadata 解支持以下特性:

房產 Description
name 必須的。 綁定參數名稱。 應該會與 name 觸發標註相同的參數值相符。
json 必須的。 中繼資料是有效的 JSON 字串。 可以包含任何任意的鍵值對,例如作者資訊、版本號、UI 提示或標籤。

範例:

@McpResourceTrigger(
        name = "context",
        uri = "file://readme.md",
        resourceName = "readme",
        description = "Application readme file",
        mimeType = "text/plain")
@McpMetadata(
        name = "context",
        json = "{\"author\": \"John Doe\", \"version\": 1.0}")

如需完整範例,請參閱範例一節。

Usage

MCP 資源觸發器可綁定以下類型:

類型 Description
ResourceInvocationContext 一個代表資源請求的物件,包括資源 URI、會話 ID 及傳輸資訊。

該 ResourceInvocationContext 類型提供以下特性:

房產 類型 Description
URI string 請求的資源的 URI。
SessionId string? 與目前資源調用相關聯的會話 ID。
運輸 Transport? 目前召喚的傳輸資訊。

mcp_resource_trigger裝飾器綁定一個上下文參數,代表 MCP 用戶端的資源請求。 觸發器可綁定以下類型: str、、 dict或 bytes。

資源處理程式函式有兩個參數:

參數 類型 Description
messages T (預設為 unknown) 觸發有效載荷由 MCP 擴充傳遞。 (前例中此參數即為此。 resourceContext)
context InvocationContext Azure Functions 調用上下文,提供日誌及其他執行時資訊。

MCP 資源觸發器將資源調用上下文綁定到函式參數。 觸發器可綁定以下類型: String或 byte[] 二進位內容。

資源 URI

MCP 資源使用 URI 來定義資源的位址。 URI 唯一識別資源,是用戶端用來請求的資源。 你可以使用任何適合你資源的 URI 方案,例如 ui:// UI 資源或 file:// 檔案類資源。

資源元資料

使用屬性 McpMetadata 來提供額外的資源元資料。 MCP 用戶端會接收這些元資料,這會影響資源內容的顯示或處理方式。

若要提供額外的資源元資料,請使用 metadata 裝飾器上的 mcp_resource_trigger 參數。 這個元資料是 JSON 序列化的字串,包含在 meta 每個資源欄位中,當用戶端呼叫 resources/list時。 它會影響資源內容的顯示或處理方式。

利用 metadata 提供額外資源元資料的選項。 這個元資料是 JSON 序列化的字串,包含在 meta 每個資源欄位中,當用戶端呼叫 resources/list時。 它會影響資源內容的顯示或處理方式。

使用 @McpMetadata 註解來提供額外的資源元資料。 這個元資料是 JSON 序列化的字串,包含在 meta 每個資源欄位中,當用戶端呼叫 resources/list時。 它會影響資源內容的顯示或處理方式。

傳回類型

MCP 資源觸發器支援以下回傳類型:

類型 Description
string 以文字內容形式回傳於 MCP ReadResourceResult中。
byte[] 以 base64 編碼的 blob 內容在 MCP ReadResourceResult中回傳。

MCP 資源觸發器支援以下回傳類型:

類型 Description
str 以文字內容形式回傳於 MCP ReadResourceResult中。
bytes 在 MCP ReadResourceResult中以二進位內容回傳。

函式應回傳包含資源內容的 ( string 例如 HTML、JSON 或純文字)。

MCP 資源觸發器支援以下回傳類型:

類型 Description
String 以文字內容形式回傳於 MCP ReadResourceResult中。
byte[] 在 MCP ReadResourceResult中以 base64 編碼的二進位內容回傳。 在返回二進位內容時,請設定 dataType = "binary" 註解。

資源探索

當函式應用程式啟動時,會向 MCP 伺服器註冊所有資源觸發函式。 用戶端透過呼叫 MCP resources/list 方法來發現可用資源。 此方法會回傳每個資源的 URI、名稱、描述、MIME 類型、大小及元資料(透過欄位)。meta 用戶端透過呼叫 resources/read 資源 URI 來讀取資源。

會議

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

如需詳細資訊,請參閱 範例。

host.json 設定

host.json 檔案包含控制MCP觸發行為的設定。 如需可用設定的詳細資訊,請參閱host.json設定一節。

MCP 工具觸發器用於 Azure Functions