Skip to content
Back to search

python-utcp

Official python implementation of UTCP. UTCP is an open standard that lets AI agents call any API directly, without extra middleware.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/universal-tool-calling-protocol--python-utcp/badge.svg)](/listings/universal-tool-calling-protocol--python-utcp)

HTML

<a href="/listings/universal-tool-calling-protocol--python-utcp"><img src="/api/listings/universal-tool-calling-protocol--python-utcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Installation

Install the core library and any required protocol plugins:

# Install core + HTTP plugin (most common)
pip install utcp utcp-http

# Install additional plugins as needed
pip install utcp-cli utcp-mcp utcp-text

Basic Usage

from utcp.utcp_client import UtcpClient

# Create client with HTTP API
client = await UtcpClient.create(config={
    "manual_call_templates": [{
        "name": "my_api",
        "call_template_type": "http",
        "url": "https://api.example.com/utcp"
    }]
})

# Call a tool
result = await client.call_tool("my_api.get_data", {"id": "123"})

# Release the connections this client opened
await client.close()

Protocol Lifetime: Shared vs. Per-Client Instances

A protocol plugin registers itself in one of two registries, and the choice decides who its state belongs to.

An instance registered with `register_communication_protocol` is **shared by every `UtcpClient` in the process**, and so is any state it keeps. That is right for state that is *meant* to be shared — a credential cache, a registry a decorator writes into — and wrong for state that belongs to one client. A shared instance lives as long as the process; no client closes it.

A protocol whose state **must not be shared between clients** registers a **factory** instead: live sessions or connections keyed per manual, child processes — anything one client's use or `close()` would take away from another. Each `UtcpClient` calls the factory once — at creation, or on first use if it was registered later — so each client gets its own instance, its own connections, and its own teardown on `close()`:

from utcp.plugins.discovery import register_communication_protocol_factory

register_communication_protocol_factory("custom_type", CustomCommunicationProtocol)

This is what makes "a client per tenant / per user / per pooled connection" actually isolate them, rather than every client reaching into one shared instance. A type registered as a factory wins over the same type registered as an instance, so a plugin migrates by moving its registration from one call to the other and callers change nothing.

`utcp-mcp` and `utcp-websocket` register this way — MCP sessions (and, for stdio, child processes) and per-manual WebSocket connections belong to the client that opened them. `utcp-http` (HTTP, SSE, streamable HTTP) and `utcp-gql` stay shared instances: the only state they keep is an OAuth token cache, which is meant to be reused across clients; every request opens its own session.

`client.close()` closes the instances the client created — every one of them, even if one fails, after which the failures are raised together as `UtcpProtocolCloseError`. If `UtcpClient.create` fails after creating them, they are closed the same way before the error is re-raised.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 717 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Universal Tool Calling Protocol (UTCP)
  2. [![Follow Org](https://img.shields.io/github/followers/universal-tool-calling-protocol?label=Follow%20Org&logo=github)](https://github.com/universal-tool-calling-protocol)
  3. [![PyPI Downloads](https://static.pepy.tech/badge/utcp)](https://pepy.tech/projects/utcp)
  4. [![License](https://img.shields.io/github/license/universal-tool-calling-protocol/python-utcp)](https://github.com/universal-tool-calling-protocol/python-utcp/blob/main/LICENSE)
  5. [![CDTM S23](https://img.shields.io/badge/CDTM-S23-0b84f3)](https://cdtm.com/)
  6. ## Introduction
  7. The Universal Tool Calling Protocol (UTCP) is a secure, scalable standard for defining and interacting with tools across a wide variety of communication protocols. UTCP 1.0.0 introduces a modular core with a plugin-based architecture, making it more extensible, testable, and easier to package.
  8. In contrast to other protocols, UTCP places a strong emphasis on:
  9. * **Scalability**: UTCP is designed to handle a large number of tools and providers without compromising performance.
  10. * **Extensibility**: A pluggable architecture allows developers to easily add new communication protocols, tool storage mechanisms, and search strategies without modifying the core library.
  11. * **Interoperability**: With a growing ecosystem of protocol plugins (including HTTP, SSE, CLI, and more), UTCP can integrate with almost any existing service or infrastructure.
  12. * **Ease of Use**: The protocol is built on simple, well-defined Pydantic models, making it easy for developers to implement and use.
  13. ![MCP vs. UTCP](https://github.com/user-attachments/assets/3cadfc19-8eea-4467-b606-66e580b89444)
  14. ## Repository Structure
  15. This repository contains the complete UTCP Python implementation:
  16. - **[`core/`](core/)** - Core `utcp` package with foundational components ([README](core/README.md))
  17. - **[`plugins/communication_protocols/`](plugins/communication_protocols/)** - Protocol-specific plugins:
  18. - [`http/`](plugins/communication_protocols/http/) - HTTP/REST, SSE, streaming, OpenAPI ([README](plugins/communication_protocols/http/README.md))
  19. - [`cli/`](plugins/communication_protocols/cli/) - Command-line tools ([README](plugins/communication_protocols/cli/README.md))
  20. - [`mcp/`](plugins/communication_protocols/mcp/) - Model Context Protocol ([README](plugins/communication_protocols/mcp/README.md))
  21. - [`text/`](plugins/communication_protocols/text/) - File-based tools ([README](plugins/communication_protocols/text/README.md))
  22. - [`socket/`](plugins/communication_protocols/socket/) - TCP/UDP (🚧 In Progress)
  23. - [`gql/`](plugins/communication_protocols/gql/) - GraphQL (🚧 In Progress)
  24. ## Architecture Overview
  25. UTCP uses a modular architecture with a core library and protocol plugins:
  26. ### Core Package (`utcp`)
  27. The [`core/`](core/) directory contains the foundational components:
  28. - **Data Models**: Pydantic models for `Tool`, `CallTemplate`, `UtcpManual`, and `Auth`
  29. - **Client Interface**: Main `UtcpClient` for tool interaction
  30. - **Plugin System**: Extensible interfaces for protocols, repositories, and search
  31. - **Default Implementations**: Built-in tool storage and search strategies
  32. ## Quick Start
  33. ### Installation
  34. Install the core library and any required protocol plugins:
  35. ```bash
  36. # Install core + HTTP plugin (most common)
  37. pip install utcp utcp-http
  38. # Install additional plugins as needed
  39. pip install utcp-cli utcp-mcp utcp-text
  40. ```
  41. ### Basic Usage
  42. ```python
  43. from utcp.utcp_client import UtcpClient
  44. # Create client with HTTP API
  45. client = await UtcpClient.create(config={
  46. "manual_call_templates": [{
  47. "name": "my_api",
  48. "call_template_type": "http",
  49. "url": "https://api.example.com/utcp"
  50. }]
  51. })
  52. # Call a tool
  53. result = await client.call_tool("my_api.get_data", {"id": "123"})
  54. # Release the connections this client opened
  55. await client.close()
  56. ```
  57. ### Protocol Lifetime: Shared vs. Per-Client Instances
  58. A protocol plugin registers itself in one of two registries, and the choice decides who its state belongs to.
  59. An instance registered with `register_communication_protocol` is **shared by every `UtcpClient` in the process**, and so is any state it keeps. That is right for state that is *meant* to be shared — a credential cache, a registry a decorator writes into — and wrong for state that belongs to one client. A shared instance lives as long as the process; no client closes it.
  60. A protocol whose state **must not be shared between clients** registers a **factory** instead: live sessions or connections keyed per manual, child processes — anything one client's use or `close()` would take away from another. Each `UtcpClient` calls the factory once — at creation, or on first use if it was registered later — so each client gets its own instance, its own connections, and its own teardown on `close()`:
  61. ```python
  62. from utcp.plugins.discovery import register_communication_protocol_factory
  63. register_communication_protocol_factory("custom_type", CustomCommunicationProtocol)
  64. ```
  65. This is what makes "a client per tenant / per user / per pooled connection" actually isolate them, rather than every client reaching into one shared instance. A type registered as a factory wins over the same type registered as an instance, so a plugin migrates by moving its registration from one call to the other and callers change nothing.
  66. `utcp-mcp` and `utcp-websocket` register this way — MCP sessions (and, for stdio, child processes) and per-manual WebSocket connections belong to the client that opened them. `utcp-http` (HTTP, SSE, streamable HTTP) and `utcp-gql` stay shared instances: the only state they keep is an OAuth token cache, which is meant to be reused across clients; every request opens its own session.
  67. `client.close()` closes the instances the client created — every one of them, even if one fails, after which the failures are raised together as `UtcpProtocolCloseError`. If `UtcpClient.create` fails after creating them, they are closed the same way before the error is re-raised.
  68. ## Protocol Plugins
  69. UTCP supports multiple communication protocols through dedicated plugins:
  70. | Plugin | Description | Status | Documentation |
  71. |--------|-------------|--------|---------------|
  72. | [`utcp-http`](plugins/communication_protocols/http/) | HTTP/REST APIs, SSE, streaming | ✅ Stable | [HTTP Plugin README](plugins/communication_protocols/http/README.md) |
  73. | [`utcp-cli`](plugins/communication_protocols/cli/) | Command-line tools | ✅ Stable | [CLI Plugin README](plugins/communication_protocols/cli/README.md) |
  74. | [`utcp-mcp`](plugins/communication_protocols/mcp/) | Model Context Protocol | ✅ Stable | [MCP Plugin README](plugins/communication_protocols/mcp/README.md) |
  75. | [`utcp-text`](plugins/communication_protocols/text/) | Local file-based tools | ✅ Stable | [Text Plugin README](plugins/communication_protocols/text/README.md) |
  76. | [`utcp-websocket`](plugins/communication_protocols/websocket/) | WebSocket real-time bidirectional communication | ✅ Stable | [WebSocket Plugin README](plugins/communication_protocols/websocket/README.md) |
  77. | [`utcp-socket`](plugins/communication_protocols/socket/) | TCP/UDP protocols | 🚧 In Progress | [Socket Plugin README](plugins/communication_protocols/socket/README.md) |
  78. | [`utcp-gql`](plugins/communication_protocols/gql/) | GraphQL APIs | 🚧 In Progress | [GraphQL Plugin README](plugins/communication_protocols/gql/README.md) |
  79. For development, you can install the packages in editable mode from the cloned repository:
  80. ```bash
  81. # Clone the repository
  82. git clone https://github.com/universal-tool-calling-protocol/python-utcp.git
  83. cd python-utcp
  84. # Install the core package in editable mode with dev dependencies
  85. pip install -e "core[dev]"
  86. # Install a specific protocol plugin in editable mode
  87. pip install -e plugins/communication_protocols/http
  88. ```
  89. ## Migration Guide from 0.x to 1.0.0
  90. Version 1.0.0 introduces several breaking changes. Follow these steps to migrate your project.
  91. 1. **Update Dependencies**: Install the new `utcp` core package and the specific protocol plugins you use (e.g., `utcp-http`, `utcp-cli`).
  92. 2. **Configuration**:
  93. * **Configuration Object**: `UtcpClient` is initialized with a `UtcpClientConfig` object, dict or a path to a JSON file containing the configuration.
  94. * **Manual Call Templates**: The `providers_file_path` option is removed. Instead of a file path, you now provide a list of `manual_call_templates` directly within the `UtcpClientConfig`.
  95. * **Terminology**: The term `provider` has been replaced with `call_template`, and `provider_type` is now `call_template_type`.
  96. * **Streamable HTTP**: The `call_template_type` `http_stream` has been renamed to `streamable_http`.
  97. 3. **Update Imports**: Change your imports to reflect the new modular structure. For example, `from utcp.client.transport_interfaces.http_transport import HttpProvider` becomes `from utcp_http.http_call_template import HttpCallTemplate`.
  98. 4. **Tool Search**: If you were using the default search, the new strategy is `TagAndDescriptionWordMatchStrategy`. This is the new default and requires no changes unless you were implementing a custom strategy.
  99. 5. **Tool Naming**: Tool names are now namespaced as `manual_name.tool_name`. The client handles this automatically.
  100. 6. **Variable Substitution Namespacing**: Variables that are substituted in different `call_templates`, are first namespaced with the name of the manual with the `_` duplicated. So a key in a tool call template called `API_KEY` from the manual `manual_1` would be converted to `manual__1_API_KEY`.
  101. ## Usage Examples
  102. ### 1. Using the UTCP Client
  103. **`config.json`** (Optional)
  104. You can define a comprehensive client configuration in a JSON file. All of these fields are optional.
  105. ```json
  106. {
  107. "variables": {
  108. "openlibrary_URL": "https://openlibrary.org/static/openapi.json"
  109. },
  110. "load_variables_from": [
  111. {
  112. "variable_loader_type": "dotenv",
  113. "env_file_path": ".env"
  114. }
  115. ],
  116. "tool_repository": {
  117. "tool_repository_type": "in_memory"
  118. },
  119. "tool_search_strategy": {
  120. "tool_search_strategy_type": "tag_and_description_word_match"
  121. },
  122. "manual_call_templates": [
  123. {
  124. "name": "openlibrary",
  125. "call_template_type": "http",
  126. "http_method": "GET",
  127. "url": "${URL}",
  128. "content_type": "application/json"
  129. },
  130. ],
  131. "post_processing": [
  132. {
  133. "tool_post_processor_type": "filter_dict",
  134. "only_include_keys": ["name", "key"],
  135. "only_include_tools": ["openlibrary.read_search_authors_json_search_authors_json_get"]
  136. }
  137. ]
  138. }
  139. ```
  140. **`client.py`**
  141. ```python
  142. import asyncio
  143. from utcp.utcp_client import UtcpClient
  144. from utcp.data.utcp_client_config import UtcpClientConfig
  145. async def main():
  146. # The UtcpClient can be created with a config file path, a dict, or a UtcpClientConfig object.
  147. # Option 1: Initialize from a config file path
  148. # client_from_file = await UtcpClient.create(config="./config.json")
  149. # Option 2: Initialize from a dictionary
  150. client_from_dict = await UtcpClient.create(config={
  151. "variables": {
  152. "openlibrary_URL": "https://openlibrary.org/static/openapi.json"
  153. },
  154. "load_variables_from": [
  155. {
  156. "variable_loader_type": "dotenv",
  157. "env_file_path": ".env"
  158. }
  159. ],
  160. "tool_repository": {
  161. "tool_repository_type": "in_memory"
  162. },
  163. "tool_search_strategy": {
  164. "tool_search_strategy_type": "tag_and_description_word_match"
  165. },
  166. "manual_call_templates": [
  167. {
  168. "name": "openlibrary",
  169. "call_template_type": "http",
  170. "http_method": "GET",
  171. "url": "${URL}",
  172. "content_type": "application/json"
  173. }
  174. ],
  175. "post_processing": [
  176. {
  177. "tool_post_processor_type": "filter_dict",
  178. "only_include_keys": ["name", "key"],
  179. "only_include_tools": ["openlibrary.read_search_authors_json_search_authors_json_get"]
  180. }
  181. ]
  182. })
  183. # Option 3: Initialize with a full-featured UtcpClientConfig object
  184. from utcp_http.http_call_template import HttpCallTemplate
  185. from utcp.data.variable_loader import VariableLoaderSerializer
  186. from utcp.interfaces.tool_post_processor import ToolPostProcessorConfigSerializer
  187. config_obj = UtcpClientConfig(
  188. variables={"openlibrary_URL": "https://openlibrary.org/static/openapi.json"},
  189. load_variables_from=[
  190. VariableLoaderSerializer().validate_dict({
  191. "variable_loader_type": "dotenv", "env_file_path": ".env"
  192. })
  193. ],
  194. manual_call_templates=[
  195. HttpCallTemplate(
  196. name="openlibrary",
  197. call_template_type="http",
  198. http_method="GET",
  199. url="${URL}",
  200. content_type="application/json"
  201. )
  202. ],
  203. post_processing=[
  204. ToolPostProcessorConfigSerializer().validate_dict({
  205. "tool_post_processor_type": "filter_dict",
  206. "only_include_keys": ["name", "key"],
  207. "only_include_tools": ["openlibrary.read_search_authors_json_search_authors_json_get"]
  208. })
  209. ]
  210. )
  211. client = await UtcpClient.create(config=config_obj)
  212. # Call a tool. The name is namespaced: `manual_name.tool_name`
  213. result = await client.call_tool(
  214. tool_name="openlibrary.read_search_authors_json_search_authors_json_get",
  215. tool_args={"q": "J. K. Rowling"}
  216. )
  217. print(result)
  218. if __name__ == "__main__":
  219. asyncio.run(main())
  220. ```
  221. ### 2. Providing a UTCP Manual
  222. A `UTCPManual` describes the tools you offer. The key change is replacing `tool_provider` with `tool_call_template`.
  223. **`server.py`**
  224. UTCP decorator version:
  225. ```python
  226. from fastapi import FastAPI
  227. from utcp_http.http_call_template import HttpCallTemplate
  228. from utcp.data.utcp_manual import UtcpManual
  229. from utcp.python_specific_tooling.tool_decorator import utcp_tool
  230. app = FastAPI()
  231. # The discovery endpoint returns the tool manual
  232. @app.get("/utcp")
  233. def utcp_discovery():
  234. return UtcpManual.create_from_decorators(manual_version="1.0.0")
  235. # The actual tool endpoint
  236. @utcp_tool(tool_call_template=HttpCallTemplate(
  237. name="get_weather",
  238. url=f"https://example.com/api/weather",
  239. http_method="GET"
  240. ), tags=["weather"])
  241. @app.get("/api/weather")
  242. def get_weather(location: str):
  243. return {"temperature": 22.5, "conditions": "Sunny"}
  244. ```
  245. No UTCP dependencies server version:
  246. ```python
  247. from fastapi import FastAPI
  248. app = FastAPI()
  249. # The discovery endpoint returns the tool manual
  250. @app.get("/utcp")
  251. def utcp_discovery():
  252. return {
  253. "manual_version": "1.0.0",
  254. "utcp_version": "1.0.2",
  255. "tools": [
  256. {
  257. "name": "get_weather",
  258. "description": "Get current weather for a location",
  259. "tags": ["weather"],
  260. "inputs": {
  261. "type": "object",
  262. "properties": {
  263. "location": {"type": "string"}
  264. }
  265. },
  266. "outputs": {
  267. "type": "object",
  268. "properties": {
  269. "temperature": {"type": "number"},
  270. "conditions": {"type": "string"}
  271. }
  272. },
  273. "tool_call_template": {
  274. "call_template_type": "http",
  275. "url": "https://example.com/api/weather",
  276. "http_method": "GET"
  277. }
  278. }
  279. ]
  280. }
  281. # The actual tool endpoint
  282. @app.get("/api/weather")
  283. def get_weather(location: str):
  284. return {"temperature": 22.5, "conditions": "Sunny"}
  285. ```
  286. ### 3. Full examples
  287. You can find full examples in the [examples repository](https://github.com/universal-tool-calling-protocol/utcp-examples).
  288. ## Protocol Specification
  289. ### `UtcpManual` and `Tool` Models
  290. The `tool_provider` object inside a `Tool` has been replaced by `tool_call_template`.
  291. ```json
  292. {
  293. "manual_version": "string",
  294. "utcp_version": "string",
  295. "tools": [
  296. {
  297. "name": "string",
  298. "description": "string",
  299. "inputs": { ... },
  300. "outputs": { ... },
  301. "tags": ["string"],
  302. "tool_call_template": {
  303. "call_template_type": "http",
  304. "url": "https://...",
  305. "http_method": "GET"
  306. }
  307. }
  308. ]
  309. }
  310. ```
  311. ## Call Template Configuration Examples
  312. Configuration examples for each protocol. Remember to replace `provider_type` with `call_template_type`.
  313. ### HTTP Call Template
  314. ```json
  315. {
  316. "name": "my_rest_api",
  317. "call_template_type": "http", // Required
  318. "url": "https://api.example.com/users/{user_id}", // Required
  319. "http_method": "POST", // Required, default: "GET"
  320. "content_type": "application/json", // Optional, default: "application/json"
  321. "allowed_communication_protocols": ["http"], // Optional, defaults to [call_template_type]. Restricts which protocols tools can use.
  322. "auth": { // Optional, authentication for the HTTP request (example using ApiKeyAuth for Bearer token)
  323. "auth_type": "api_key",
  324. "api_key": "Bearer $API_KEY", // Required
  325. "var_name": "Authorization", // Optional, default: "X-Api-Key"
  326. "location": "header" // Optional, default: "header"
  327. },
  328. "auth_tools": { // Optional, authentication for converted tools, if this call template points to an openapi spec that should be automatically converted to a utcp manual (applied only to endpoints requiring auth per OpenAPI spec)
  329. "auth_type": "api_key",
  330. "api_key": "Bearer $TOOL_API_KEY", // Required
  331. "var_name": "Authorization", // Optional, default: "X-Api-Key"
  332. "location": "header" // Optional, default: "header"
  333. },
  334. "headers": { // Optional
  335. "X-Custom-Header": "value"
  336. },
  337. "body_field": "body", // Optional, default: "body"
  338. "header_fields": ["user_id"] // Optional
  339. }
  340. ```
  341. ### SSE (Server-Sent Events) Call Template
  342. ```json
  343. {
  344. "name": "my_sse_stream",
  345. "call_template_type": "sse", // Required
  346. "url": "https://api.example.com/events", // Required
  347. "event_type": "message", // Optional
  348. "reconnect": true, // Optional, default: true
  349. "retry_timeout": 30000, // Optional, default: 30000 (ms)
  350. "auth": { // Optional, example using BasicAuth
  351. "auth_type": "basic",
  352. "username": "${USERNAME}", // Required
  353. "password": "${PASSWORD}" // Required
  354. },
  355. "headers": { // Optional
  356. "X-Client-ID": "12345"
  357. },
  358. "body_field": null, // Optional
  359. "header_fields": [] // Optional
  360. }
  361. ```
  362. ### Streamable HTTP Call Template
  363. Note the name change from `http_stream` to `streamable_http`.
  364. ```json
  365. {
  366. "name": "streaming_data_source",
  367. "call_template_type": "streamable_http", // Required
  368. "url": "https://api.example.com/stream", // Required
  369. "http_method": "POST", // Optional, default: "GET"
  370. "content_type": "application/octet-stream", // Optional, default: "application/octet-stream"
  371. "chunk_size": 4096, // Optional, default: 4096
  372. "timeout": 60000, // Optional, default: 60000 (ms)
  373. "auth": null, // Optional
  374. "headers": {}, // Optional
  375. "body_field": "data", // Optional
  376. "header_fields": [] // Optional
  377. }
  378. ```
  379. ### CLI Call Template
  380. ```json
  381. {
  382. "name": "multi_step_cli_tool",
  383. "call_template_type": "cli", // Required
  384. "commands": [ // Required - sequential command execution
  385. {
  386. "command": "git clone UTCP_ARG_repo_url_UTCP_END temp_repo",
  387. "append_to_final_output": false
  388. },
  389. {
  390. "command": "cd temp_repo && find . -name '*.py' | wc -l"
  391. // Last command output returned by default
  392. }
  393. ],
  394. "env_vars": { // Optional
  395. "GIT_AUTHOR_NAME": "UTCP Bot",
  396. "API_KEY": "${MY_API_KEY}"
  397. },
  398. "working_dir": "/tmp", // Optional
  399. "auth": null // Optional (always null for CLI)
  400. }
  401. ```
  402. **CLI Protocol Features:**
  403. - **Multi-command execution**: Commands run sequentially in single subprocess
  404. - **Cross-platform**: PowerShell on Windows, Bash on Unix/Linux/macOS
  405. - **State preservation**: Directory changes (`cd`) persist between commands
  406. - **Argument placeholders**: `UTCP_ARG_argname_UTCP_END` format
  407. - **Output referencing**: Access previous outputs with `$CMD_0_OUTPUT`, `$CMD_1_OUTPUT`
  408. - **Flexible output control**: Choose which command outputs to include in final result
  409. ### Text Call Template
  410. ```json
  411. {
  412. "name": "my_text_manual",
  413. "call_template_type": "text", // Required
  414. "file_path": "./manuals/my_manual.json", // Required
  415. "auth": null, // Optional (always null for Text)
  416. "auth_tools": { // Optional, authentication for generated tools from OpenAPI specs
  417. "auth_type": "api_key",
  418. "api_key": "Bearer ${API_TOKEN}",
  419. "var_name": "Authorization",
  420. "location": "header"
  421. }
  422. }
  423. ```
  424. ### MCP (Model Context Protocol) Call Template
  425. ```json
  426. {
  427. "name": "my_mcp_server",
  428. "call_template_type": "mcp", // Required
  429. "config": { // Required
  430. "mcpServers": {
  431. "server_name": {
  432. "transport": "stdio",
  433. "command": ["python", "-m", "my_mcp_server"]
  434. }
  435. }
  436. },
  437. "auth": { // Optional, example using OAuth2
  438. "auth_type": "oauth2",
  439. "token_url": "https://auth.example.com/token", // Required
  440. "client_id": "${CLIENT_ID}", // Required
  441. "client_secret": "${CLIENT_SECRET}", // Required
  442. "scope": "read:tools" // Optional
  443. }
  444. }
  445. ```
  446. ## Security: Protocol Restrictions
  447. UTCP provides fine-grained control over which communication protocols each manual can use through the `allowed_communication_protocols` field. This prevents potentially dangerous protocol escalation (e.g., an HTTP-based manual accidentally calling CLI tools).
  448. ### Default Behavior (Secure by Default)
  449. When `allowed_communication_protocols` is not set or is empty, a manual can only register and call tools that use the **same protocol type** as the manual itself:
  450. ```python
  451. from utcp_http.http_call_template import HttpCallTemplate
  452. # This manual can ONLY register/call HTTP tools (default restriction)
  453. http_manual = HttpCallTemplate(
  454. name="my_api",
  455. call_template_type="http",
  456. url="https://api.example.com/utcp"
  457. # allowed_communication_protocols not set → defaults to ["http"]
  458. )
  459. ```
  460. ### Allowing Multiple Protocols
  461. To allow a manual to work with tools from multiple protocols, explicitly set `allowed_communication_protocols`:
  462. ```python
  463. from utcp_http.http_call_template import HttpCallTemplate
  464. # This manual can register/call both HTTP and CLI tools
  465. multi_protocol_manual = HttpCallTemplate(
  466. name="flexible_manual",
  467. call_template_type="http",
  468. url="https://api.example.com/utcp",
  469. allowed_communication_protocols=["http", "cli"] # Explicitly allow both
  470. )
  471. ```
  472. ### JSON Configuration
  473. ```json
  474. {
  475. "name": "my_api",
  476. "call_template_type": "http",
  477. "url": "https://api.example.com/utcp",
  478. "allowed_communication_protocols": ["http", "cli", "mcp"]
  479. }
  480. ```
  481. ### Behavior Summary
  482. | `allowed_communication_protocols` | Manual Type | Allowed Tool Protocols |
  483. |----------------------------------|-------------|------------------------|
  484. | Not set / `null` | `"http"` | Only `"http"` |
  485. | `[]` (empty) | `"http"` | Only `"http"` |
  486. | `["http", "cli"]` | `"http"` | `"http"` and `"cli"` |
  487. | `["http", "cli", "mcp"]` | `"cli"` | `"http"`, `"cli"`, and `"mcp"` |
  488. ### Registration Filtering
  489. During `register_manual()`, tools that don't match the allowed protocols are automatically filtered out with a warning:
  490. ```
  491. WARNING - Tool 'dangerous_tool' uses communication protocol 'cli' which is not in
  492. allowed protocols ['http'] for manual 'my_api'. Tool will not be registered.
  493. ```
  494. ### Call-Time Validation
  495. Even if a tool somehow exists in the repository, calling it will fail if its protocol is not allowed:
  496. ```python
  497. # Raises ValueError: Tool 'my_api.some_cli_tool' uses communication protocol 'cli'
  498. # which is not allowed by manual 'my_api'. Allowed protocols: ['http']
  499. await client.call_tool("my_api.some_cli_tool", {"arg": "value"})
  500. ```
  501. ## Testing
  502. The testing structure has been updated to reflect the new core/plugin split.
  503. ### Running Tests
  504. To run all tests for the core library and all plugins:
  505. ```bash
  506. # Ensure you have installed all dev dependencies
  507. python -m pytest
  508. ```
  509. To run tests for a specific package (e.g., the core library):
  510. ```bash
  511. python -m pytest core/tests/
  512. ```
  513. To run tests for a specific plugin (e.g., HTTP):
  514. ```bash
  515. python -m pytest plugins/communication_protocols/http/tests/ -v
  516. ```
  517. To run tests with coverage:
  518. ```bash
  519. python -m pytest --cov=utcp --cov-report=xml
  520. ```
  521. ## Build
  522. The build process now involves building each package (`core` and `plugins`) separately if needed, though they are published to PyPI independently.
  523. 1. Create and activate a virtual environment.
  524. 2. Install build dependencies: `pip install build`.
  525. 3. Navigate to the package directory (e.g., `cd core`).
  526. 4. Run the build: `python -m build`.
  527. 5. The distributable files (`.whl` and `.tar.gz`) will be in the `dist/` directory.
  528. ## OpenAPI Ingestion - Zero Infrastructure Tool Integration
  529. 🚀 **Transform any existing REST API into UTCP tools without server modifications!**
  530. UTCP's OpenAPI ingestion feature automatically converts OpenAPI 2.0/3.0 specifications into UTCP tools, enabling AI agents to interact with existing APIs directly - no wrapper servers, no API changes, no additional infrastructure required.
  531. ### Quick Start with OpenAPI
  532. ```python
  533. from utcp_http.openapi_converter import OpenApiConverter
  534. import aiohttp
  535. # Convert any OpenAPI spec to UTCP tools
  536. async def convert_api():
  537. async with aiohttp.ClientSession() as session:
  538. async with session.get("https://api.github.com/openapi.json") as response:
  539. openapi_spec = await response.json()
  540. converter = OpenApiConverter(openapi_spec)
  541. manual = converter.convert()
  542. print(f"Generated {len(manual.tools)} tools from GitHub API!")
  543. return manual
  544. # Or use UTCP Client configuration for automatic detection
  545. from utcp.utcp_client import UtcpClient
  546. client = await UtcpClient.create(config={
  547. "manual_call_templates": [{
  548. "name": "github",
  549. "call_template_type": "http",
  550. "url": "https://api.github.com/openapi.json",
  551. "auth_tools": { # Authentication for generated tools requiring auth
  552. "auth_type": "api_key",
  553. "api_key": "Bearer ${GITHUB_TOKEN}",
  554. "var_name": "Authorization",
  555. "location": "header"
  556. }
  557. }]
  558. })
  559. ```
  560. ### Key Benefits
  561. - ✅ **Zero Infrastructure**: No servers to deploy or maintain
  562. - ✅ **Direct API Calls**: Native performance, no proxy overhead
  563. - ✅ **Automatic Conversion**: OpenAPI schemas → UTCP tools
  564. - ✅ **Selective Authentication**: Only protected endpoints get auth, public endpoints remain accessible
  565. - ✅ **Authentication Preserved**: API keys, OAuth2, Basic auth supported
  566. - ✅ **Multi-format Support**: JSON, YAML, OpenAPI 2.0/3.0
  567. - ✅ **Batch Processing**: Convert multiple APIs simultaneously
  568. ### Multiple Ingestion Methods
  569. 1. **Direct Converter**: `OpenApiConverter` class for full control
  570. 2. **Remote URLs**: Fetch and convert specs from any URL
  571. 3. **Client Configuration**: Include specs directly in UTCP config
  572. 4. **Batch Processing**: Process multiple specs programmatically
  573. 5. **File-based**: Convert local JSON/YAML specifications
  574. 📖 **[Complete OpenAPI Ingestion Guide](docs/openapi-ingestion.md)** - Detailed examples and advanced usage
  575. ---
  576. ## [Contributors](https://www.utcp.io/about)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.