Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions azurefunctions-extensions-mcp/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions azurefunctions-extensions-mcp/MANIFEST.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
recursive-include azure *.py *.pyi
recursive-include tests *.py
include LICENSE README.md
102 changes: 102 additions & 0 deletions azurefunctions-extensions-mcp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Azure Functions Extensions Bindings ServiceBus library for Python
This library allows ServiceBus Triggers in Python Function Apps to recognize and bind to client types from the
Azure ServiceBus sdk.

The SDK types can be generated from:

* ServiceBus Triggers

The supported ServiceBus SDK types include:

* ServiceBusReceivedMessage

[Source code](https://github.com/Azure/azure-functions-python-extensions/tree/dev/azurefunctions-extensions-bindings-servicebus)
|
[Package (PyPi)](https://pypi.org/project/azurefunctions-extensions-bindings-servicebus/)
| [Samples](https://github.com/Azure/azure-functions-python-extensions/tree/dev/azurefunctions-extensions-bindings-servicebus/samples)


## Getting started

### Prerequisites
* Python 3.9 or later is required to use this package. For more details, please read our page on [Python Functions version support policy](https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=isolated-process%2Cv4&pivots=programming-language-python#languages).

* You must have an [Azure subscription](https://azure.microsoft.com/free/) and a
[ServiceBus Resource](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus?tabs=isolated-process%2Cextensionv5%2Cextensionv3&pivots=programming-language-python) to use this package.

### Install the package
Install the Azure Functions Extensions Bindings ServiceBus library for Python with pip:

```bash
pip install azurefunctions-extensions-bindings-servicebus
```


### Bind to the SDK-type
The Azure Functions Extensions Bindings ServiceBus library for Python allows you to create a function app with a ServiceBus Trigger
and define the type as a ServiceBusReceivedMessage. Instead of receiving
a ServiceBusMessage, when the function is executed, the type returned will be the defined SDK-type and have all the
properties and methods available as seen in the Azure ServiceBus library for Python.


```python
import logging
import azure.functions as func
import azurefunctions.extensions.bindings.servicebus as servicebus

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

@app.service_bus_queue_trigger(arg_name="receivedmessage",
queue_name="QUEUE_NAME",
connection="SERVICEBUS_CONNECTION")
def servicebus_queue_trigger(receivedmessage: servicebus.ServiceBusReceivedMessage):
logging.info("Python ServiceBus queue trigger processed message.")
logging.info("Receiving: %s\n"
"Body: %s\n"
"Enqueued time: %s\n"
"Lock Token: %s\n"
"Locked until : %s\n"
"Message ID: %s\n"
"Sequence number: %s\n",
receivedmessage,
receivedmessage.body,
receivedmessage.enqueued_time_utc,
receivedmessage.lock_token,
receivedmessage.locked_until,
receivedmessage.message_id,
receivedmessage.sequence_number)
```

## Troubleshooting
### General
The SDK-types raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).

This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`.

## Next steps

### More sample code

Get started with our [ServiceBus samples](https://github.com/Azure/azure-functions-python-extensions/tree/dev/azurefunctions-extensions-bindings-servicebus/samples).

Several samples are available in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure ServiceBus:

* [servicebus_samples_single](https://github.com/Azure/azure-functions-python-extensions/tree/dev/azurefunctions-extensions-bindings-servicebus/samples/servicebus_samples_single) - Examples for using the ServiceBusReceivedMessage type:
* From ServiceBus Queue Trigger (Single Message)
* From ServiceBus Topic Trigger (Single Message)

* [servicebus_samples_batch](https://github.com/Azure/azure-functions-python-extensions/tree/dev/azurefunctions-extensions-bindings-servicebus/samples/service_samples_batch) - Examples for interacting with batches:
* From ServiceBus Queue Trigger (Batch)
* From ServiceBus Topic Trigger (Batch)


### Additional documentation
For more information on the Azure ServiceBus SDK, see the [Azure ServiceBus SDK documentation](https://learn.microsoft.com/en-us/python/api/overview/azure/servicebus-readme?view=azure-python) on docs.microsoft.com
and the [Azure ServiceBus README](https://github.com/Azure/azure-sdk-for-python/blob/azure-servicebus_7.14.1/sdk/servicebus/azure-servicebus/README.md).

## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
1 change: 1 addition & 0 deletions azurefunctions-extensions-mcp/azurefunctions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .decorators.mcp_app import McpApp, MCPToolContext

__all__ = [
"McpApp",
"MCPToolContext",
]

__version__ = '0.0.0a1'
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

MCP_TOOL_TRIGGER = "mcpToolTrigger"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Decorator definitions for MCP Function Apps."""
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from ..constants import (
MCP_TOOL_TRIGGER
)

from typing import Any, Dict, Optional
from azure.functions.decorators.core import Trigger, DataType


class MCPToolTrigger(Trigger):

@staticmethod
def get_binding_name() -> str:
return MCP_TOOL_TRIGGER

def __init__(self,
name: str,
tool_name: str,
description: Optional[str] = None,
tool_properties: Optional[str] = None,
data_type: Optional[DataType] = None,
**kwargs):
self.tool_name = tool_name
self.description = description
self.tool_properties = tool_properties
super().__init__(name=name, data_type=data_type)


# MCP-specific context object
class MCPToolContext(Dict[str, Any]):
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from ..utils import _extract_type_and_description
from .mcp import MCPToolTrigger, MCPToolContext

import inspect
import json
from typing import Callable

from azure.functions import FunctionRegister, Blueprint, AuthLevel


# Map Python types to MCP property types
_TYPE_MAPPING = {
int: "integer",
float: "number",
str: "string",
bool: "boolean",
}

class McpApp(Blueprint, FunctionRegister):
"""
MCP-specific app object.
Extends FunctionRegister to reuse function registration and trigger infrastructure.
"""

def __init__(self, auth_level=AuthLevel.ANONYMOUS):
super().__init__(auth_level=auth_level)

def mcp_tool(self) -> Callable[[Callable], Callable]:
"""
Decorator to register an MCP tool function.

Automatically:
- Infers tool name from function name
- Extracts first line of docstring as description
- Extracts parameters and types for tool properties
- Handles MCPToolContext injection
"""

def decorator(target_func: Callable) -> Callable:
# Extract function metadata
sig = inspect.signature(target_func)
tool_name = target_func.__name__
description = (target_func.__doc__ or "").strip().split("\n")[0]

# Build tool properties metadata
tool_properties = []
for param_name, param in sig.parameters.items():
param_type_hint = param.annotation if param.annotation != inspect.Parameter.empty else str
actual_type, param_description = _extract_type_and_description(param_name, param_type_hint)
if actual_type is MCPToolContext:
continue # context is injected, not a property
property_type = _TYPE_MAPPING.get(actual_type, "string")
tool_properties.append({
"propertyName": param_name,
"propertyType": property_type,
"description": param_description,
})

tool_properties_json = json.dumps(tool_properties)

# Wrapper function for MCP trigger
def wrapper(context: str) -> str:
try:
content = json.loads(context)
arguments = content.get("arguments", {})
kwargs = {}

for param_name, param in sig.parameters.items():
param_type_hint = param.annotation if param.annotation != inspect.Parameter.empty else str
actual_type, _ = _extract_type_and_description(param_name, param_type_hint)

if actual_type is MCPToolContext:
kwargs[param_name] = content
elif param_name in arguments:
kwargs[param_name] = arguments[param_name]
else:
return f"Error: Missing required parameter '{param_name}' for '{tool_name}'"

result = target_func(**kwargs)
return str(result)

except Exception as e:
return f"Error executing function '{tool_name}': {str(e)}"

wrapper.__name__ = target_func.__name__
wrapper.__doc__ = target_func.__doc__

# Register as MCP trigger using existing azure-functions infrastructure
fb = self._configure_function_builder(lambda fb: fb)(wrapper)
fb.add_trigger(
trigger=MCPToolTrigger(
name="context",
tool_name=tool_name,
description=description,
tool_properties=tool_properties_json
)
)

return fb

return decorator
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Any, Tuple, get_args, get_origin, Annotated


# Helper to extract actual type and description from Annotated types
def _extract_type_and_description(param_name: str, type_hint: Any) -> Tuple[Any, str]:
if get_origin(type_hint) is Annotated:
args = get_args(type_hint)
actual_type = args[0]
# Use first string annotation as description if present
param_description = next((a for a in args[1:] if isinstance(a, str)), f"The {param_name} parameter.")
return actual_type, param_description
return type_hint, f"The {param_name} parameter."
49 changes: 49 additions & 0 deletions azurefunctions-extensions-mcp/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
[build-system]
requires = ["setuptools >= 61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "func-mcp-test"
dynamic = ["version"]
requires-python = ">=3.10"
authors = [{ name = "Azure Functions team at Microsoft Corp.", email = "azurefunctions@microsoft.com"}]
description = "MCP Python worker extension for Azure Functions."
readme = "README.md"
license = {text = "MIT License"}
classifiers= [
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Programming Language :: Python :: 3.13',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Environment :: Web Environment',
'Development Status :: 5 - Production/Stable',
]
dependencies = [
'azure-functions>=1.24.0'
]

[project.optional-dependencies]
dev = [
'flake8',
'mypy',
'pytest',
'pytest-cov',
'coverage',
'pytest-instafail',
'pre-commit'
]

[tool.setuptools.dynamic]
version = {attr = "azurefunctions.extensions.mcp.__version__"}

[tool.setuptools.packages.find]
exclude = [
'azurefunctions.extensions',
'azurefunctions', 'tests', 'samples'
]
1 change: 1 addition & 0 deletions azurefunctions-extensions-mcp/samples/.funcignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.venv
Loading