Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In this quickstart, you create a custom remote Model Context Protocol (MCP) server from a template project using the Azure Developer CLI (azd). The MCP server uses the Azure Functions MCP server extension to provide tools for AI models, agents, and assistants. After running the project locally and verifying your code using GitHub Copilot, you deploy it to a new serverless function app in Azure Functions that follows current best practices for secure and scalable deployments.
Tip
Functions also enables you to deploy an existing MCP server code project to a Flex Consumption plan app without having to make changes to your code project. For more information, see Quickstart: Host existing MCP servers on Azure Functions.
Because the new app runs on the Flex Consumption plan, which follows a pay-for-what-you-use billing model, completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
Important
While creating custom MCP servers is supported for all Functions languages, this quickstart scenario currently only has examples for C#, Python, and TypeScript. To complete this quickstart, select one of these supported languages at the top of the article.
This article supports version 4 of the Node.js programming model for Azure Functions.
This article supports version 2 of the Python programming model for Azure Functions.
Prerequisites
- Java 17 Developer Kit
- If you use another supported version of Java, you must update the project's pom.xml file.
- Set the
JAVA_HOMEenvironment variable to the install location of the correct version of the Java Development Kit (JDK).
- Apache Maven 3.8.x
Visual Studio Code with these extensions:
Azure Functions extension. This extension requires Azure Functions Core Tools and attempts to install it when not available.
Azure CLI. You can also run Azure CLI commands in Azure Cloud Shell.
An Azure account with an active subscription. Create an account for free.
Initialize the project
Use the azd init command to create a local Azure Functions code project from a template.
- In Visual Studio Code, open a folder or workspace where you want to create your project.
In the Terminal, run this
azd initcommand:azd init --template remote-mcp-functions-dotnet -e mcpserver-dotnetThis command pulls the project files from the template repository and initializes the project in the current folder. The
-eflag sets a name for the current environment. Inazd, the environment maintains a unique deployment context for your app, and you can define more than one. It's also used in the name of the resource group you create in Azure.
In your local terminal or command prompt, run this
azd initcommand:azd init --template remote-mcp-functions-java -e mcpserver-javaThis command pulls the project files from the template repository and initializes the project in the current folder. The
-eflag sets a name for the current environment. Inazd, the environment maintains a unique deployment context for your app, and you can define more than one. It's also used in names of the resources you create in Azure.
In your local terminal or command prompt, run this
azd initcommand:azd init --template remote-mcp-functions-typescript -e mcpserver-tsThis command pulls the project files from the template repository and initializes the project in the current folder. The
-eflag sets a name for the current environment. Inazd, the environment maintains a unique deployment context for your app, and you can define more than one. It's also used in names of the resources you create in Azure.
In your local terminal or command prompt, run this
azd initcommand:azd init --template remote-mcp-functions-python -e mcpserver-pythonThis command pulls the project files from the template repository and initializes the project in the current folder. The
-eflag sets a name for the current environment. Inazd, the environment maintains a unique deployment context for your app, and you can define more than one. It's also used in names of the resources you create in Azure.
Start the storage emulator
Use the Azurite emulator to simulate an Azure Storage account connection when running your code project locally.
If you haven't already, install Azurite.
Press F1. In the command palette, search for and run the command
Azurite: Startto start the local storage emulator.
Run your MCP server locally
Visual Studio Code integrates with Azure Functions Core tools to let you run this project on your local development computer by using the Azurite emulator.
To start the function locally, press F5 or the Run and Debug icon in the left-hand side Activity bar. The Terminal panel displays the output from Core Tools. Your app starts in the Terminal panel, and you can see the name of the functions that are running locally.
Make a note of the local MCP server endpoint (like
http://localhost:7071/runtime/webhooks/mcp), which you use to configure GitHub Copilot in Visual Studio Code.
Verify using GitHub Copilot
To verify your code, add the running project as an MCP server for GitHub Copilot in Visual Studio Code:
Press F1. In the command palette, search for and run MCP: Add Server.
Choose HTTP (Server-Sent Events) for the transport type.
Enter the URL of the MCP endpoint you copied in the previous step.
Use the generated Server ID and select Workspace to save the MCP server connection to your Workspace settings.
Open the command palette and run MCP: List Servers and verify that the server you added is listed and running.
In Copilot chat, select Agent mode and run this prompt:
Say HelloWhen prompted to run the tool, select Allow in this Workspace so you don't have to keep granting permission. The prompt runs and returns a
Hello Worldresponse and function execution information is written to the logs.Now, select some code in one of your project files and run this prompt:
Save this snippet as snippet1Copilot stores the snippet and responds to your request with information about how to retrieve the snippet by using the
getSnippetstool. Again, you can review the function execution in the logs and verify that thesaveSnippetsfunction ran.In Copilot chat, run this prompt:
Retrieve snippet1 and apply to NewFileCopilot retrieves the snippets, adds it to a file called
NewFile, and does whatever else it thinks is needed to make the code snippet work in your project. The Functions logs show that thegetSnippetsendpoint was called.When you're done testing, press Ctrl+C to stop the Functions host.
Review the code (optional)
You can review the code that defines the MCP server tools:
The function code for the MCP server tools is defined in the src folder. The McpToolTrigger attribute exposes the functions as MCP Server tools:
[Function(nameof(SayHello))]
public string SayHello(
[McpToolTrigger(HelloToolName, HelloToolDescription)] ToolInvocationContext context
)
{
logger.LogInformation("Saying hello");
return "Hello I am MCP Tool!";
}
[Function(nameof(GetSnippet))]
public object GetSnippet(
[McpToolTrigger(GetSnippetToolName, GetSnippetToolDescription)]
ToolInvocationContext context,
[BlobInput(BlobPath)] string snippetContent
)
{
return snippetContent;
}
[Function(nameof(SaveSnippet))]
[BlobOutput(BlobPath)]
public string SaveSnippet(
[McpToolTrigger(SaveSnippetToolName, SaveSnippetToolDescription)]
ToolInvocationContext context,
[McpToolProperty(SnippetNamePropertyName, SnippetNamePropertyDescription, true)]
string name,
[McpToolProperty(SnippetPropertyName, SnippetPropertyDescription, true)]
string snippet
)
{
return snippet;
}
}
You can view the complete project template in the Azure Functions .NET MCP Server GitHub repository.
The function code for the MCP server tools is defined in the src/main/java/com/function/ folder. The @McpToolTrigger annotation exposes the functions as MCP Server tools:
description = "The messages to be logged.",
isRequired = true,
isArray = true)
String messages,
final ExecutionContext functionExecutionContext
) {
functionExecutionContext.getLogger().info("Hello, World!");
functionExecutionContext.getLogger().info("Tool Name: " + mcpToolInvocationContext.getName());
functionExecutionContext.getLogger().info("Transport Type: " + mcpToolInvocationContext.getTransportType());
// Handle different transport types
if (mcpToolInvocationContext.isHttpStreamable()) {
functionExecutionContext.getLogger().info("Session ID: " + mcpToolInvocationContext.getSessionid());
} else if (mcpToolInvocationContext.isHttpSse()) {
if (mcpToolInvocationContext.getClientinfo() != null) {
functionExecutionContext.getLogger().info("Client: " +
mcpToolInvocationContext.getClientinfo().get("name").getAsString() + " v" +
// Write the snippet content to the output blob
outputBlob.setValue(snippet);
return "Successfully saved snippet '" + snippetName + "' with " + snippet.length() + " characters.";
}
/**
* Azure Function that handles retrieving a text snippet from Azure Blob Storage.
* <p>
* The function is triggered by an MCP Tool Trigger. The snippet name is provided
* as an MCP tool property, and the snippet content is read from the blob at the
* path derived from the snippet name.
*
* @param mcpToolInvocationContext The JSON input from the MCP tool trigger.
* @param snippetName The name of the snippet to retrieve, provided as an MCP tool property.
* @param inputBlob The Azure Blob input binding that fetches the snippet content.
* @param functionExecutionContext The execution context for logging.
*/
@FunctionName("GetSnippets")
@StorageAccount("AzureWebJobsStorage")
public String getSnippet(
@McpToolTrigger(
name = "getSnippets",
description = "Gets a text snippet from your snippets collection.")
String mcpToolInvocationContext,
@McpToolProperty(
name = SNIPPET_NAME_PROPERTY_NAME,
propertyType = "string",
description = "The name of the snippet.",
isRequired = true)
String snippetName,
@BlobInput(name = "inputBlob", path = BLOB_PATH)
String inputBlob,
final ExecutionContext functionExecutionContext
) {
// Log the entire incoming JSON for debugging
functionExecutionContext.getLogger().info(mcpToolInvocationContext);
// Log the snippet name and the fetched snippet content from the blob
You can view the complete project template in the Azure Functions Java MCP Server GitHub repository.
The function code for the MCP server tools is defined in the src/function_app.py file. The MCP function annotations expose these functions as MCP Server tools:
tool_properties_save_snippets_json = json.dumps([prop.to_dict() for prop in tool_properties_save_snippets_object])
tool_properties_get_snippets_json = json.dumps([prop.to_dict() for prop in tool_properties_get_snippets_object])
@app.generic_trigger(
arg_name="context",
type="mcpToolTrigger",
toolName="hello_mcp",
description="Hello world.",
toolProperties="[]",
)
def hello_mcp(context) -> None:
"""
@app.generic_trigger(
arg_name="context",
type="mcpToolTrigger",
toolName="save_snippet",
description="Save a snippet with a name.",
toolProperties=tool_properties_save_snippets_json,
)
@app.generic_output_binding(arg_name="file", type="blob", connection="AzureWebJobsStorage", path=_BLOB_PATH)
def save_snippet(file: func.Out[str], context) -> str:
content = json.loads(context)
snippet_name_from_args = content["arguments"][_SNIPPET_NAME_PROPERTY_NAME]
snippet_content_from_args = content["arguments"][_SNIPPET_PROPERTY_NAME]
if not snippet_name_from_args:
return "No snippet name provided"
if not snippet_content_from_args:
return "No snippet content provided"
file.set(snippet_content_from_args)
logging.info(f"Saved snippet: {snippet_content_from_args}")
return f"Snippet '{snippet_content_from_args}' saved successfully"
You can view the complete project template in the Azure Functions Python MCP Server GitHub repository.
The function code for the MCP server tools is defined in the src folder. The MCP function registration exposes these functions as MCP Server tools:
export async function mcpToolHello(_toolArguments:unknown, context: InvocationContext): Promise<string> {
console.log(_toolArguments);
// Get name from the tool arguments
const mcptoolargs = context.triggerMetadata.mcptoolargs as {
name?: string;
};
const name = mcptoolargs?.name;
console.info(`Hello ${name}, I am MCP Tool!`);
return `Hello ${name || 'World'}, I am MCP Tool!`;
}
// Register the hello tool
app.mcpTool('hello', {
toolName: 'hello',
description: 'Simple hello world MCP Tool that responses with a hello message.',
toolProperties:{
name: arg.string().describe('Required property to identify the caller.').optional()
},
handler: mcpToolHello
});
// SaveSnippet function - saves a snippet with a name
export async function saveSnippet(
_toolArguments: unknown,
context: InvocationContext
): Promise<string> {
console.info("Saving snippet");
// Get snippet name and content from the tool arguments
const mcptoolargs = context.triggerMetadata.mcptoolargs as {
snippetname?: string;
snippet?: string;
};
const snippetName = mcptoolargs?.snippetname;
const snippet = mcptoolargs?.snippet;
if (!snippetName) {
return "No snippet name provided";
}
if (!snippet) {
return "No snippet content provided";
}
// Save the snippet to blob storage using the output binding
context.extraOutputs.set(blobOutputBinding, snippet);
console.info(`Saved snippet: ${snippetName}`);
return snippet;
}
You can view the complete project template in the Azure Functions TypeScript MCP Server GitHub repository.
After verifying the MCP server tools locally, you can publish the project to Azure.
Deploy to Azure
This project is configured to use the azd up command to deploy this project to a new function app in a Flex Consumption plan in Azure. The project includes a set of Bicep files that azd uses to create a secure deployment to a Flex consumption plan that follows best practices.
In Visual Studio Code, press F1 to open the command palette. Search for and run the command
Azure Developer CLI (azd): Package, Provison and Deploy (up). Then, sign in by using your Azure account.If you're not already signed in, authenticate with your Azure account.
When prompted, provide these required deployment parameters:
Parameter Description Azure subscription Subscription in which your resources are created. Azure location Azure region in which to create the resource group that contains the new Azure resources. Only regions that currently support the Flex Consumption plan are shown. After the command completes successfully, you see links to the resources you created.
Connect to your remote MCP server
Your MCP server is now running in Azure. When you access the tools, you need to include a system key in your request. This key provides a degree of access control for clients accessing your remote MCP server. After you get this key, you can connect GitHub Copilot to your remote server.
Run this script that uses
azdand the Azure CLI to print out both the MCP server URL and the system key (mcp_extension) required to access the tools:eval $(azd env get-values --output dotenv) MCP_EXTENSION_KEY=$(az functionapp keys list --resource-group $AZURE_RESOURCE_GROUP \ --name $AZURE_FUNCTION_NAME --query "systemKeys.mcp_extension" -o tsv) printf "MCP Server URL: %s\n" "https://$SERVICE_API_NAME.azurewebsites.net/runtime/webhooks/mcp" printf "MCP Server key: %s\n" "$MCP_EXTENSION_KEY"In Visual Studio Code, press F1 to open the command palette, search for and run the command
MCP: Open Workspace Folder MCP Configuraton, which opens themcp.jsonconfiguration file.In the
mcp.jsonconfiguration, find the named MCP server you added earlier, change theurlvalue to your remote MCP server URL, and add aheaders.x-functions-keyelement, which contains your copied MCP server access key, as in this example:{ "servers": { "remote-mcp-function": { "type": "http", "url": "https://contoso.azurewebsites.net/runtime/webhooks/mcp", "headers": { "x-functions-key": "A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u..." } } } }Select the Start button above your server name in the open
mcp.jsonto restart the remote MCP server, this time using your deployed app.
Verify your deployment
You can now have GitHub Copilot use your remote MCP tools just as you did locally, but now the code runs securely in Azure. Replay the same commands you used earlier to ensure everything works correctly.
Clean up resources
When you're done working with your MCP server and related resources, use this command to delete the function app and its related resources from Azure to avoid incurring further costs:
azd down --no-prompt
Note
The --no-prompt option instructs azd to delete your resource group without confirmation from you. This command doesn't affect your local code project.