cogno-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Sudoers AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-mcp
3
+ Version: 0.1.0
4
+ Summary: Bridge an MCP (Model Context Protocol) server's tools to cogno-anima's tool contract — MCPDispatcher implements ToolDispatcher + ToolPolicyDispatcher so the EGO/cogno-soma see MCP tools as ordinary tools. SDK-free mapping; thin stdio/HTTP/SSE transports over the official mcp SDK.
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-mcp
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-mcp
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-mcp/issues
11
+ Keywords: mcp,model-context-protocol,tools,agents,cogno,llm
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: cogno-anima<0.2,>=0.1
25
+ Provides-Extra: mcp
26
+ Requires-Dist: mcp>=1.0; extra == "mcp"
27
+ Provides-Extra: dev
28
+ Requires-Dist: mcp>=1.0; extra == "dev"
29
+ Requires-Dist: pytest>=8.0; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
32
+ Requires-Dist: ruff>=0.5; extra == "dev"
33
+ Requires-Dist: mypy>=1.8; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # cogno-mcp
37
+
38
+ **Bridge an MCP server's tools to the Cogno tool contract.**
39
+
40
+ The third tool source for the Cogno stack — alongside in-process skills
41
+ ([`cogno-cortex`](https://github.com/sudoers-ai/cogno-cortex)) and the host's native
42
+ functions. `MCPDispatcher` exposes any [MCP](https://modelcontextprotocol.io) server's
43
+ tools as a `cogno-anima` `ToolDispatcher`, so the EGO / `cogno-soma` see MCP tools as
44
+ ordinary tools and never speak the protocol.
45
+
46
+ The valuable part — schema conversion, `CallToolResult → ToolResult` mapping, and
47
+ policy (read-only / destructive) from MCP tool annotations — is **SDK-free** and
48
+ fully tested with fakes. The thin transport helpers (stdio / HTTP / SSE) are the
49
+ only place the official `mcp` SDK is used; transport is the SDK's job, not ours.
50
+
51
+ ```
52
+ MCP server ──(stdio/HTTP/SSE)──▶ MCPDispatcher ──▶ ToolDispatcher ──▶ EGO / cogno-soma
53
+ (implements cogno-anima's contract)
54
+ ```
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install "cogno-mcp[mcp]" # [mcp] pulls the official MCP SDK (for transport)
60
+ ```
61
+
62
+ > `cogno-anima` (the contract) is a runtime dep not yet on PyPI — install it from
63
+ > git first; see `.github/workflows/ci.yml`. Without the `[mcp]` extra the
64
+ > `MCPDispatcher` still works against any session you provide; the transport
65
+ > helpers raise a clear `MCPUnavailableError`.
66
+
67
+ ## Use
68
+
69
+ ```python
70
+ import sys
71
+ from cogno_mcp import MCPDispatcher, stdio_session
72
+
73
+ async with stdio_session(sys.executable, args=["my_server.py"]) as session:
74
+ dispatcher = await MCPDispatcher.create(session) # lists + caches tools
75
+
76
+ dispatcher.tools_schema() # OpenAI tool defs the EGO offers
77
+ dispatcher.is_mutating("wipe") # from the tool's readOnlyHint
78
+ dispatcher.requires_confirmation("wipe") # from its destructiveHint
79
+
80
+ await pipe.run_turn(ctx, cfg, dispatcher=dispatcher) # cogno-soma
81
+ ```
82
+
83
+ Transports: `stdio_session(command, args=...)` (subprocess), `http_session(url)`
84
+ (Streamable HTTP), `sse_session(url)` (legacy SSE). Each is an async context manager
85
+ that connects, `initialize()`s, and tears down on exit — the host owns the lifecycle.
86
+
87
+ ## Mapping
88
+
89
+ | MCP | → cogno-anima |
90
+ |---|---|
91
+ | `Tool.name/description/inputSchema` | `tools_schema()` OpenAI function def |
92
+ | `CallToolResult.content` (text blocks) | `ToolResult.output` |
93
+ | `CallToolResult.isError = True` | recoverable `ToolResult(ok=False)` |
94
+ | transport / protocol exception | raises `MCPDispatchError` (EGO propagates) |
95
+ | unknown tool name | recoverable `ToolResult(ok=False)` |
96
+ | `annotations.readOnlyHint` | `is_mutating` (absent/false → conservative true) |
97
+ | `annotations.destructiveHint = True` | `requires_confirmation` (drives the EGO gate) |
98
+
99
+ ## Skills + MCP + native together
100
+
101
+ Each source is a `ToolDispatcher`; merge them per persona:
102
+
103
+ ```python
104
+ from cogno_anima.tools import CompositeDispatcher
105
+ dispatcher = CompositeDispatcher([cortex_dispatcher, mcp_dispatcher, native_dispatcher])
106
+ ```
107
+
108
+ The `ToolDispatcher` contract is the unifier — skill / MCP / native are just sources.
109
+
110
+ ## The Cogno ecosystem
111
+
112
+ `cogno-mcp` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
113
+ small, composable, Apache-2.0 libraries that together form a complete
114
+ conversational-agent platform. Each library owns a single concern and stays
115
+ infra-agnostic; a **host** assembles them into a running agent:
116
+
117
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
118
+
119
+ The open-source libraries are the organs; the **host is the body** that joins
120
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
121
+ private product layer, but it holds no special powers: everything it does rides
122
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
123
+ you can assemble a body of your own.
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ pip install -e ".[dev]"
129
+ pytest tests/unit -q # SDK-free dispatcher logic against fakes
130
+ pytest tests/integration -q # MCPDispatcher vs a real FastMCP server over stdio
131
+ ruff check cogno_mcp tests && mypy cogno_mcp
132
+ python examples/host_min.py # spawns a local MCP server and calls a tool
133
+ ```
134
+
135
+ Apache-2.0.
@@ -0,0 +1,100 @@
1
+ # cogno-mcp
2
+
3
+ **Bridge an MCP server's tools to the Cogno tool contract.**
4
+
5
+ The third tool source for the Cogno stack — alongside in-process skills
6
+ ([`cogno-cortex`](https://github.com/sudoers-ai/cogno-cortex)) and the host's native
7
+ functions. `MCPDispatcher` exposes any [MCP](https://modelcontextprotocol.io) server's
8
+ tools as a `cogno-anima` `ToolDispatcher`, so the EGO / `cogno-soma` see MCP tools as
9
+ ordinary tools and never speak the protocol.
10
+
11
+ The valuable part — schema conversion, `CallToolResult → ToolResult` mapping, and
12
+ policy (read-only / destructive) from MCP tool annotations — is **SDK-free** and
13
+ fully tested with fakes. The thin transport helpers (stdio / HTTP / SSE) are the
14
+ only place the official `mcp` SDK is used; transport is the SDK's job, not ours.
15
+
16
+ ```
17
+ MCP server ──(stdio/HTTP/SSE)──▶ MCPDispatcher ──▶ ToolDispatcher ──▶ EGO / cogno-soma
18
+ (implements cogno-anima's contract)
19
+ ```
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install "cogno-mcp[mcp]" # [mcp] pulls the official MCP SDK (for transport)
25
+ ```
26
+
27
+ > `cogno-anima` (the contract) is a runtime dep not yet on PyPI — install it from
28
+ > git first; see `.github/workflows/ci.yml`. Without the `[mcp]` extra the
29
+ > `MCPDispatcher` still works against any session you provide; the transport
30
+ > helpers raise a clear `MCPUnavailableError`.
31
+
32
+ ## Use
33
+
34
+ ```python
35
+ import sys
36
+ from cogno_mcp import MCPDispatcher, stdio_session
37
+
38
+ async with stdio_session(sys.executable, args=["my_server.py"]) as session:
39
+ dispatcher = await MCPDispatcher.create(session) # lists + caches tools
40
+
41
+ dispatcher.tools_schema() # OpenAI tool defs the EGO offers
42
+ dispatcher.is_mutating("wipe") # from the tool's readOnlyHint
43
+ dispatcher.requires_confirmation("wipe") # from its destructiveHint
44
+
45
+ await pipe.run_turn(ctx, cfg, dispatcher=dispatcher) # cogno-soma
46
+ ```
47
+
48
+ Transports: `stdio_session(command, args=...)` (subprocess), `http_session(url)`
49
+ (Streamable HTTP), `sse_session(url)` (legacy SSE). Each is an async context manager
50
+ that connects, `initialize()`s, and tears down on exit — the host owns the lifecycle.
51
+
52
+ ## Mapping
53
+
54
+ | MCP | → cogno-anima |
55
+ |---|---|
56
+ | `Tool.name/description/inputSchema` | `tools_schema()` OpenAI function def |
57
+ | `CallToolResult.content` (text blocks) | `ToolResult.output` |
58
+ | `CallToolResult.isError = True` | recoverable `ToolResult(ok=False)` |
59
+ | transport / protocol exception | raises `MCPDispatchError` (EGO propagates) |
60
+ | unknown tool name | recoverable `ToolResult(ok=False)` |
61
+ | `annotations.readOnlyHint` | `is_mutating` (absent/false → conservative true) |
62
+ | `annotations.destructiveHint = True` | `requires_confirmation` (drives the EGO gate) |
63
+
64
+ ## Skills + MCP + native together
65
+
66
+ Each source is a `ToolDispatcher`; merge them per persona:
67
+
68
+ ```python
69
+ from cogno_anima.tools import CompositeDispatcher
70
+ dispatcher = CompositeDispatcher([cortex_dispatcher, mcp_dispatcher, native_dispatcher])
71
+ ```
72
+
73
+ The `ToolDispatcher` contract is the unifier — skill / MCP / native are just sources.
74
+
75
+ ## The Cogno ecosystem
76
+
77
+ `cogno-mcp` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
78
+ small, composable, Apache-2.0 libraries that together form a complete
79
+ conversational-agent platform. Each library owns a single concern and stays
80
+ infra-agnostic; a **host** assembles them into a running agent:
81
+
82
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
83
+
84
+ The open-source libraries are the organs; the **host is the body** that joins
85
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
86
+ private product layer, but it holds no special powers: everything it does rides
87
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
88
+ you can assemble a body of your own.
89
+
90
+ ## Development
91
+
92
+ ```bash
93
+ pip install -e ".[dev]"
94
+ pytest tests/unit -q # SDK-free dispatcher logic against fakes
95
+ pytest tests/integration -q # MCPDispatcher vs a real FastMCP server over stdio
96
+ ruff check cogno_mcp tests && mypy cogno_mcp
97
+ python examples/host_min.py # spawns a local MCP server and calls a tool
98
+ ```
99
+
100
+ Apache-2.0.
@@ -0,0 +1,25 @@
1
+ """cogno-mcp — expose an MCP server's tools as a cogno-anima ToolDispatcher.
2
+
3
+ The third tool source (alongside in-process skills via ``cogno-cortex`` and the
4
+ host's native functions): ``MCPDispatcher`` bridges any MCP server to cogno-anima's
5
+ ``ToolDispatcher`` contract, so the EGO / cogno-soma see MCP tools as ordinary
6
+ tools. The mapping logic is SDK-free; the thin transport helpers (stdio/HTTP/SSE)
7
+ use the official ``mcp`` SDK. Merge with other sources via
8
+ ``cogno_anima.tools.CompositeDispatcher``.
9
+ """
10
+
11
+ from cogno_mcp.dispatcher import MCPDispatcher
12
+ from cogno_mcp.errors import MCPDispatchError, MCPError, MCPUnavailableError
13
+ from cogno_mcp.transports import http_session, sse_session, stdio_session
14
+
15
+ __all__ = [
16
+ "MCPDispatcher",
17
+ "stdio_session",
18
+ "http_session",
19
+ "sse_session",
20
+ "MCPError",
21
+ "MCPUnavailableError",
22
+ "MCPDispatchError",
23
+ ]
24
+
25
+ __version__ = "0.1.0"
@@ -0,0 +1,157 @@
1
+ """``MCPDispatcher`` — expose an MCP server's tools as a cogno-anima ToolDispatcher.
2
+
3
+ This is the bridge (symmetric to cogno-cortex's ``CortexDispatcher``): the EGO /
4
+ cogno-soma see an MCP server's tools as ordinary tools and never speak MCP. It
5
+ implements cogno-anima's ``ToolDispatcher`` + ``ToolPolicyDispatcher``.
6
+
7
+ Deliberately **SDK-free**: it works against any *session* object that quacks like
8
+ ``mcp.ClientSession`` (``await list_tools()`` / ``await call_tool(name, args)``) and
9
+ any *tool* that quacks like ``mcp.types.Tool`` (``.name`` / ``.description`` /
10
+ ``.inputSchema`` / ``.annotations``). Only the transport helpers in
11
+ ``cogno_mcp.transports`` import the ``mcp`` SDK — so the valuable mapping logic
12
+ (schema conversion, ``CallToolResult`` → ``ToolResult``, policy from annotations)
13
+ is fully unit-testable with fakes, and the transport is the official SDK's job.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ import json
20
+ from typing import Any, Optional, Sequence
21
+
22
+ from cogno_anima.types import ToolResult
23
+
24
+ from cogno_mcp.errors import MCPDispatchError
25
+
26
+ # Default cap on the server-supplied tool ``description`` rendered into the EGO prompt: a
27
+ # compromised/verbose MCP server could otherwise inject an unbounded blob (prompt injection +
28
+ # num_ctx starvation). The host can raise/lower it per dispatcher.
29
+ DEFAULT_MAX_DESCRIPTION_CHARS = 2048
30
+
31
+
32
+ def _content_to_text(result: Any) -> str:
33
+ """Flatten an MCP ``CallToolResult`` into a single text payload.
34
+
35
+ Joins text content blocks; non-text blocks are noted by type. Falls back to the
36
+ structured content when there is no textual content.
37
+ """
38
+ parts: list[str] = []
39
+ for block in getattr(result, "content", None) or []:
40
+ btype = getattr(block, "type", None)
41
+ if btype == "text":
42
+ parts.append(getattr(block, "text", ""))
43
+ elif btype:
44
+ parts.append(f"[{btype}]")
45
+ if parts:
46
+ return "\n".join(p for p in parts if p)
47
+ structured = getattr(result, "structuredContent", None)
48
+ if structured is None:
49
+ return ""
50
+ # JSON so the model consuming this sees valid syntax, not Python repr ({'a': True}).
51
+ try:
52
+ return json.dumps(structured, ensure_ascii=False, default=str)
53
+ except (TypeError, ValueError):
54
+ return str(structured)
55
+
56
+
57
+ class MCPDispatcher:
58
+ """A cogno-anima ``ToolDispatcher`` (+ ``ToolPolicyDispatcher``) over one MCP session."""
59
+
60
+ def __init__(self, session: Any, tools: Sequence[Any], *,
61
+ names: Optional[Sequence[str]] = None,
62
+ call_timeout: Optional[float] = 30.0,
63
+ trust_annotations: bool = True,
64
+ max_description_chars: int = DEFAULT_MAX_DESCRIPTION_CHARS) -> None:
65
+ """
66
+ Args:
67
+ session: an established MCP client session (``initialize()`` already called).
68
+ tools: the server's tools (from ``list_tools()``), cached for sync schema access.
69
+ names: the subset of tool names to expose; ``None`` → expose all.
70
+ call_timeout: seconds to wait for a tool call / list before treating the server as
71
+ hung (→ fatal ``MCPDispatchError``). ``None`` disables the timeout (wait forever).
72
+ trust_annotations: when ``False``, IGNORE the server's ``readOnlyHint``/
73
+ ``destructiveHint`` — every tool is treated as mutating AND confirmation-requiring.
74
+ Set it for a less-trusted third-party server: the MCP SDK warns that clients must
75
+ not make tool-safety decisions from an untrusted server's own annotations.
76
+ max_description_chars: cap on the tool ``description`` rendered into the EGO prompt.
77
+ """
78
+ self._session = session
79
+ self._tools: dict[str, Any] = {t.name: t for t in tools}
80
+ self._names = list(names) if names is not None else list(self._tools)
81
+ self._call_timeout = call_timeout
82
+ self._trust_annotations = trust_annotations
83
+ self._max_description_chars = max_description_chars
84
+
85
+ @classmethod
86
+ async def create(cls, session: Any, *, names: Optional[Sequence[str]] = None,
87
+ call_timeout: Optional[float] = 30.0,
88
+ trust_annotations: bool = True,
89
+ max_description_chars: int = DEFAULT_MAX_DESCRIPTION_CHARS) -> "MCPDispatcher":
90
+ """Connect to the session's tool list and build a dispatcher."""
91
+ try:
92
+ resp = await asyncio.wait_for(session.list_tools(), timeout=call_timeout)
93
+ except asyncio.TimeoutError as exc:
94
+ raise MCPDispatchError("list_tools", {}, exc) from exc
95
+ return cls(session, resp.tools, names=names, call_timeout=call_timeout,
96
+ trust_annotations=trust_annotations, max_description_chars=max_description_chars)
97
+
98
+ def tools_schema(self) -> list[dict]:
99
+ schemas: list[dict] = []
100
+ for name in self._names:
101
+ tool = self._tools.get(name)
102
+ if tool is None:
103
+ continue
104
+ desc = (getattr(tool, "description", "") or "")[:self._max_description_chars]
105
+ schemas.append({
106
+ "type": "function",
107
+ "function": {
108
+ "name": tool.name,
109
+ "description": desc,
110
+ "parameters": getattr(tool, "inputSchema", None) or {
111
+ "type": "object", "properties": {}},
112
+ },
113
+ })
114
+ return schemas
115
+
116
+ async def execute(self, name: str, arguments: dict) -> ToolResult:
117
+ if name not in self._tools:
118
+ # hallucinated / unknown name → recoverable, the EGO self-corrects
119
+ return ToolResult(output="", ok=False, error=f"unknown tool: {name}")
120
+ side_effect = self.is_mutating(name)
121
+ try:
122
+ result = await asyncio.wait_for(
123
+ self._session.call_tool(name, arguments), timeout=self._call_timeout)
124
+ except asyncio.TimeoutError as exc: # hung server → fatal, don't pin the EGO worker forever
125
+ raise MCPDispatchError(name, arguments, exc) from exc
126
+ except Exception as exc: # transport/protocol fault → fatal, EGO propagates
127
+ raise MCPDispatchError(name, arguments, exc) from exc
128
+ text = _content_to_text(result)
129
+ if getattr(result, "isError", False):
130
+ # a tool-level error is a recoverable business failure
131
+ return ToolResult(output="", ok=False, error=text or "tool error",
132
+ side_effect=side_effect)
133
+ return ToolResult(output=text, ok=True, side_effect=side_effect)
134
+
135
+ # ── ToolPolicyDispatcher ──────────────────────────────────────────────
136
+ def is_mutating(self, name: str) -> bool:
137
+ if not self._trust_annotations:
138
+ return True # untrusted server → assume every tool mutates
139
+ ann = getattr(self._tools.get(name), "annotations", None)
140
+ # read-only hint True → not mutating; otherwise conservative (assume mutating)
141
+ return getattr(ann, "readOnlyHint", None) is not True
142
+
143
+ def requires_confirmation(self, name: str) -> bool:
144
+ # Confirm a tool the server EXPLICITLY marks destructive (``destructiveHint=True``). The
145
+ # convention across the ecosystem's own servers is that additive writes set only
146
+ # ``readOnlyHint=False`` (no destructiveHint) and are NOT auto-confirmed — the host layer
147
+ # (e.g. its ConfirmingDispatcher) decides which additive commits need an OK. Do NOT treat a
148
+ # missing destructiveHint as destructive: it would gate-B-hold every additive write
149
+ # (add_income, update_status, …) that the host expects to commit / confirm via prompt.
150
+ # For a LESS-TRUSTED server the host opts into ``trust_annotations=False`` → confirm every
151
+ # mutating tool (the SDK warns not to trust an untrusted server's own safety hints).
152
+ if not self.is_mutating(name):
153
+ return False
154
+ if not self._trust_annotations:
155
+ return True # untrusted server → always confirm a mutating tool
156
+ ann = getattr(self._tools.get(name), "annotations", None)
157
+ return getattr(ann, "destructiveHint", None) is True
@@ -0,0 +1,24 @@
1
+ """Errors for the MCP adapter.
2
+
3
+ ``MCPDispatchError`` is re-exported from cogno-anima so a transport/infra fault
4
+ raised here matches the EGO's fatal-error contract (the EGO propagates it, vs.
5
+ wrapping a stray exception in ``ToolExecutionError``). ``MCPUnavailableError`` is
6
+ raised when the optional ``mcp`` SDK is not installed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from cogno_anima.errors import MCPDispatchError
12
+
13
+ __all__ = ["MCPError", "MCPUnavailableError", "MCPDispatchError"]
14
+
15
+
16
+ class MCPError(RuntimeError):
17
+ """Base class for cogno-mcp errors that are not the anima dispatch fault."""
18
+
19
+
20
+ class MCPUnavailableError(MCPError):
21
+ """The ``mcp`` SDK is required for transport but is not installed.
22
+
23
+ Install it with ``pip install "cogno-mcp[mcp]"``.
24
+ """
File without changes
@@ -0,0 +1,68 @@
1
+ """Transport helpers — establish an MCP ``ClientSession`` over stdio / HTTP / SSE.
2
+
3
+ These are the only place the optional ``mcp`` SDK is imported (lazily), so the
4
+ ``MCPDispatcher`` stays SDK-free. Each is an async context manager that connects,
5
+ initializes the session, and yields it; the host owns the lifecycle:
6
+
7
+ async with stdio_session("python", args=["server.py"]) as session:
8
+ dispatcher = await MCPDispatcher.create(session)
9
+ await pipe.run_turn(ctx, cfg, dispatcher=dispatcher)
10
+
11
+ The connection (and the server subprocess, for stdio) is torn down on exit.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from contextlib import asynccontextmanager
17
+ from typing import AsyncIterator, Optional, Sequence
18
+
19
+ from cogno_mcp.errors import MCPUnavailableError
20
+
21
+
22
+ def _imports():
23
+ try:
24
+ from mcp import ClientSession # noqa: F401
25
+ except ImportError as exc: # pragma: no cover - exercised via the unit guard
26
+ raise MCPUnavailableError(
27
+ 'the "mcp" SDK is required for transport: pip install "cogno-mcp[mcp]"') from exc
28
+ return ClientSession
29
+
30
+
31
+ @asynccontextmanager
32
+ async def stdio_session(
33
+ command: str, *, args: Optional[Sequence[str]] = None,
34
+ env: Optional[dict] = None,
35
+ ) -> AsyncIterator:
36
+ """Spawn an MCP server as a subprocess (stdio transport) and yield a session."""
37
+ ClientSession = _imports()
38
+ from mcp.client.stdio import StdioServerParameters, stdio_client
39
+
40
+ params = StdioServerParameters(command=command, args=list(args or []), env=env)
41
+ async with stdio_client(params) as (read, write):
42
+ async with ClientSession(read, write) as session:
43
+ await session.initialize()
44
+ yield session
45
+
46
+
47
+ @asynccontextmanager
48
+ async def http_session(url: str, *, headers: Optional[dict] = None) -> AsyncIterator:
49
+ """Connect to an MCP server over Streamable HTTP and yield a session."""
50
+ ClientSession = _imports()
51
+ from mcp.client.streamable_http import streamablehttp_client
52
+
53
+ async with streamablehttp_client(url, headers=headers) as (read, write, _):
54
+ async with ClientSession(read, write) as session:
55
+ await session.initialize()
56
+ yield session
57
+
58
+
59
+ @asynccontextmanager
60
+ async def sse_session(url: str, *, headers: Optional[dict] = None) -> AsyncIterator:
61
+ """Connect to an MCP server over SSE (legacy transport) and yield a session."""
62
+ ClientSession = _imports()
63
+ from mcp.client.sse import sse_client
64
+
65
+ async with sse_client(url, headers=headers) as (read, write):
66
+ async with ClientSession(read, write) as session:
67
+ await session.initialize()
68
+ yield session
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-mcp
3
+ Version: 0.1.0
4
+ Summary: Bridge an MCP (Model Context Protocol) server's tools to cogno-anima's tool contract — MCPDispatcher implements ToolDispatcher + ToolPolicyDispatcher so the EGO/cogno-soma see MCP tools as ordinary tools. SDK-free mapping; thin stdio/HTTP/SSE transports over the official mcp SDK.
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-mcp
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-mcp
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-mcp/issues
11
+ Keywords: mcp,model-context-protocol,tools,agents,cogno,llm
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: cogno-anima<0.2,>=0.1
25
+ Provides-Extra: mcp
26
+ Requires-Dist: mcp>=1.0; extra == "mcp"
27
+ Provides-Extra: dev
28
+ Requires-Dist: mcp>=1.0; extra == "dev"
29
+ Requires-Dist: pytest>=8.0; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
32
+ Requires-Dist: ruff>=0.5; extra == "dev"
33
+ Requires-Dist: mypy>=1.8; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # cogno-mcp
37
+
38
+ **Bridge an MCP server's tools to the Cogno tool contract.**
39
+
40
+ The third tool source for the Cogno stack — alongside in-process skills
41
+ ([`cogno-cortex`](https://github.com/sudoers-ai/cogno-cortex)) and the host's native
42
+ functions. `MCPDispatcher` exposes any [MCP](https://modelcontextprotocol.io) server's
43
+ tools as a `cogno-anima` `ToolDispatcher`, so the EGO / `cogno-soma` see MCP tools as
44
+ ordinary tools and never speak the protocol.
45
+
46
+ The valuable part — schema conversion, `CallToolResult → ToolResult` mapping, and
47
+ policy (read-only / destructive) from MCP tool annotations — is **SDK-free** and
48
+ fully tested with fakes. The thin transport helpers (stdio / HTTP / SSE) are the
49
+ only place the official `mcp` SDK is used; transport is the SDK's job, not ours.
50
+
51
+ ```
52
+ MCP server ──(stdio/HTTP/SSE)──▶ MCPDispatcher ──▶ ToolDispatcher ──▶ EGO / cogno-soma
53
+ (implements cogno-anima's contract)
54
+ ```
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install "cogno-mcp[mcp]" # [mcp] pulls the official MCP SDK (for transport)
60
+ ```
61
+
62
+ > `cogno-anima` (the contract) is a runtime dep not yet on PyPI — install it from
63
+ > git first; see `.github/workflows/ci.yml`. Without the `[mcp]` extra the
64
+ > `MCPDispatcher` still works against any session you provide; the transport
65
+ > helpers raise a clear `MCPUnavailableError`.
66
+
67
+ ## Use
68
+
69
+ ```python
70
+ import sys
71
+ from cogno_mcp import MCPDispatcher, stdio_session
72
+
73
+ async with stdio_session(sys.executable, args=["my_server.py"]) as session:
74
+ dispatcher = await MCPDispatcher.create(session) # lists + caches tools
75
+
76
+ dispatcher.tools_schema() # OpenAI tool defs the EGO offers
77
+ dispatcher.is_mutating("wipe") # from the tool's readOnlyHint
78
+ dispatcher.requires_confirmation("wipe") # from its destructiveHint
79
+
80
+ await pipe.run_turn(ctx, cfg, dispatcher=dispatcher) # cogno-soma
81
+ ```
82
+
83
+ Transports: `stdio_session(command, args=...)` (subprocess), `http_session(url)`
84
+ (Streamable HTTP), `sse_session(url)` (legacy SSE). Each is an async context manager
85
+ that connects, `initialize()`s, and tears down on exit — the host owns the lifecycle.
86
+
87
+ ## Mapping
88
+
89
+ | MCP | → cogno-anima |
90
+ |---|---|
91
+ | `Tool.name/description/inputSchema` | `tools_schema()` OpenAI function def |
92
+ | `CallToolResult.content` (text blocks) | `ToolResult.output` |
93
+ | `CallToolResult.isError = True` | recoverable `ToolResult(ok=False)` |
94
+ | transport / protocol exception | raises `MCPDispatchError` (EGO propagates) |
95
+ | unknown tool name | recoverable `ToolResult(ok=False)` |
96
+ | `annotations.readOnlyHint` | `is_mutating` (absent/false → conservative true) |
97
+ | `annotations.destructiveHint = True` | `requires_confirmation` (drives the EGO gate) |
98
+
99
+ ## Skills + MCP + native together
100
+
101
+ Each source is a `ToolDispatcher`; merge them per persona:
102
+
103
+ ```python
104
+ from cogno_anima.tools import CompositeDispatcher
105
+ dispatcher = CompositeDispatcher([cortex_dispatcher, mcp_dispatcher, native_dispatcher])
106
+ ```
107
+
108
+ The `ToolDispatcher` contract is the unifier — skill / MCP / native are just sources.
109
+
110
+ ## The Cogno ecosystem
111
+
112
+ `cogno-mcp` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
113
+ small, composable, Apache-2.0 libraries that together form a complete
114
+ conversational-agent platform. Each library owns a single concern and stays
115
+ infra-agnostic; a **host** assembles them into a running agent:
116
+
117
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
118
+
119
+ The open-source libraries are the organs; the **host is the body** that joins
120
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
121
+ private product layer, but it holds no special powers: everything it does rides
122
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
123
+ you can assemble a body of your own.
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ pip install -e ".[dev]"
129
+ pytest tests/unit -q # SDK-free dispatcher logic against fakes
130
+ pytest tests/integration -q # MCPDispatcher vs a real FastMCP server over stdio
131
+ ruff check cogno_mcp tests && mypy cogno_mcp
132
+ python examples/host_min.py # spawns a local MCP server and calls a tool
133
+ ```
134
+
135
+ Apache-2.0.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ cogno_mcp/__init__.py
5
+ cogno_mcp/dispatcher.py
6
+ cogno_mcp/errors.py
7
+ cogno_mcp/py.typed
8
+ cogno_mcp/transports.py
9
+ cogno_mcp.egg-info/PKG-INFO
10
+ cogno_mcp.egg-info/SOURCES.txt
11
+ cogno_mcp.egg-info/dependency_links.txt
12
+ cogno_mcp.egg-info/requires.txt
13
+ cogno_mcp.egg-info/top_level.txt
@@ -0,0 +1,12 @@
1
+ cogno-anima<0.2,>=0.1
2
+
3
+ [dev]
4
+ mcp>=1.0
5
+ pytest>=8.0
6
+ pytest-asyncio>=0.23.0
7
+ pytest-cov>=5.0
8
+ ruff>=0.5
9
+ mypy>=1.8
10
+
11
+ [mcp]
12
+ mcp>=1.0
@@ -0,0 +1 @@
1
+ cogno_mcp
@@ -0,0 +1,77 @@
1
+ [project]
2
+ name = "cogno-mcp"
3
+ version = "0.1.0"
4
+ description = "Bridge an MCP (Model Context Protocol) server's tools to cogno-anima's tool contract — MCPDispatcher implements ToolDispatcher + ToolPolicyDispatcher so the EGO/cogno-soma see MCP tools as ordinary tools. SDK-free mapping; thin stdio/HTTP/SSE transports over the official mcp SDK."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Vinicius Vale" }]
10
+ maintainers = [{ name = "Sudoers AI" }]
11
+ keywords = ["mcp", "model-context-protocol", "tools", "agents", "cogno", "llm"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Topic :: Software Development :: Libraries",
20
+ "Operating System :: OS Independent",
21
+ "Typing :: Typed",
22
+ ]
23
+ # The MCPDispatcher mapping needs only cogno-anima (ToolResult/MCPDispatchError).
24
+ # The official `mcp` SDK is an optional extra — required only for the transport
25
+ # helpers (stdio/HTTP/SSE), lazy-imported so the dispatcher works SDK-free.
26
+ dependencies = [
27
+ "cogno-anima>=0.1,<0.2",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/sudoers-ai/cogno-mcp"
32
+ Repository = "https://github.com/sudoers-ai/cogno-mcp"
33
+ Issues = "https://github.com/sudoers-ai/cogno-mcp/issues"
34
+
35
+ [project.optional-dependencies]
36
+ mcp = ["mcp>=1.0"]
37
+ dev = [
38
+ "mcp>=1.0",
39
+ "pytest>=8.0",
40
+ "pytest-asyncio>=0.23.0",
41
+ "pytest-cov>=5.0",
42
+ "ruff>=0.5",
43
+ "mypy>=1.8",
44
+ ]
45
+
46
+ [build-system]
47
+ requires = ["setuptools>=77.0.3", "wheel"]
48
+ build-backend = "setuptools.build_meta"
49
+
50
+ [tool.setuptools.packages.find]
51
+ include = ["cogno_mcp*"]
52
+
53
+ [tool.setuptools.package-data]
54
+ cogno_mcp = ["py.typed"]
55
+
56
+ [tool.pytest.ini_options]
57
+ asyncio_mode = "auto"
58
+ testpaths = ["tests"]
59
+ pythonpath = ["."]
60
+
61
+ [tool.coverage.run]
62
+ # The transport helpers are thin glue over the official mcp SDK, exercised by the
63
+ # gated integration job (a real server over stdio), not the unit job.
64
+ omit = ["cogno_mcp/transports.py"]
65
+
66
+ [tool.ruff]
67
+ line-length = 110
68
+ target-version = "py310"
69
+
70
+ [tool.ruff.lint]
71
+ select = ["E4", "E7", "E9", "F"]
72
+
73
+ [tool.mypy]
74
+ python_version = "3.10"
75
+ ignore_missing_imports = true
76
+ files = ["cogno_mcp"]
77
+ warn_unused_ignores = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+