lu-mcp-server 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,3 @@
1
+ __pycache__/
2
+ dist/
3
+ *.egg-info/
@@ -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 the Licensor for inclusion in the Work by the copyright
52
+ owner or by an individual or Legal Entity authorized to submit on behalf
53
+ of 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 Rafa & Cervella
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,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: lu-mcp-server
3
+ Version: 0.1.0
4
+ Summary: MCP server for Lingua Universale protocol verification -- verify AI agent communication with session types
5
+ Project-URL: Homepage, https://github.com/rafapra3008/cervellaswarm
6
+ Project-URL: Documentation, https://rafapra3008.github.io/cervellaswarm/
7
+ Project-URL: Repository, https://github.com/rafapra3008/cervellaswarm
8
+ Project-URL: Issues, https://github.com/rafapra3008/cervellaswarm/issues
9
+ Author-email: CervellaSwarm <noreply@cervellaswarm.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: ai-agents,formal-methods,mcp,protocol-verification,session-types
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: cervellaswarm-lingua-universale>=0.3.3
21
+ Requires-Dist: mcp[cli]>=1.0.0
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=7.0; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # lu-mcp-server
27
+
28
+ MCP server for [Lingua Universale](https://github.com/rafapra3008/cervellaswarm) protocol verification.
29
+
30
+ Verify AI agent communication with session types -- mathematical proofs, not trust.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install lu-mcp-server
36
+ ```
37
+
38
+ ## Configure
39
+
40
+ ### Claude Code
41
+
42
+ ```bash
43
+ claude mcp add lu-mcp-server -- lu-mcp-server
44
+ ```
45
+
46
+ ### Claude Desktop
47
+
48
+ Add to `claude_desktop_config.json`:
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "lu-mcp-server": {
54
+ "command": "lu-mcp-server"
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ ### Cursor / Windsurf
61
+
62
+ Add to your MCP settings:
63
+
64
+ ```json
65
+ {
66
+ "lu-mcp-server": {
67
+ "command": "lu-mcp-server"
68
+ }
69
+ }
70
+ ```
71
+
72
+ ## Tools
73
+
74
+ ### `lu_load_protocol`
75
+
76
+ Parse a `.lu` protocol definition and extract its structure.
77
+
78
+ ### `lu_verify_message`
79
+
80
+ Check if a message is valid in the context of an ongoing session.
81
+
82
+ ### `lu_check_properties`
83
+
84
+ Verify formal safety properties (always terminates, no deadlock, etc.).
85
+
86
+ ### `lu_list_templates`
87
+
88
+ Browse 20 standard library protocols across 5 categories.
89
+
90
+ ## Example
91
+
92
+ ```
93
+ protocol OrderProcessing:
94
+ roles: customer, warehouse, payment
95
+ customer asks warehouse to check availability
96
+ warehouse returns stock status to customer
97
+ when customer decides:
98
+ in_stock:
99
+ customer asks payment to process order
100
+ payment returns confirmation to customer
101
+ out_of_stock:
102
+ customer sends cancellation to warehouse
103
+ properties:
104
+ always terminates
105
+ no deadlock
106
+ all roles participate
107
+ ```
108
+
109
+ ## Links
110
+
111
+ - [Playground](https://rafapra3008.github.io/cervellaswarm/) -- try LU in your browser
112
+ - [PyPI](https://pypi.org/project/cervellaswarm-lingua-universale/) -- core package
113
+ - [VS Code](https://marketplace.visualstudio.com/items?itemName=cervellaswarm.lingua-universale) -- editor extension
114
+
115
+ ## License
116
+
117
+ Apache 2.0
@@ -0,0 +1,92 @@
1
+ # lu-mcp-server
2
+
3
+ MCP server for [Lingua Universale](https://github.com/rafapra3008/cervellaswarm) protocol verification.
4
+
5
+ Verify AI agent communication with session types -- mathematical proofs, not trust.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install lu-mcp-server
11
+ ```
12
+
13
+ ## Configure
14
+
15
+ ### Claude Code
16
+
17
+ ```bash
18
+ claude mcp add lu-mcp-server -- lu-mcp-server
19
+ ```
20
+
21
+ ### Claude Desktop
22
+
23
+ Add to `claude_desktop_config.json`:
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "lu-mcp-server": {
29
+ "command": "lu-mcp-server"
30
+ }
31
+ }
32
+ }
33
+ ```
34
+
35
+ ### Cursor / Windsurf
36
+
37
+ Add to your MCP settings:
38
+
39
+ ```json
40
+ {
41
+ "lu-mcp-server": {
42
+ "command": "lu-mcp-server"
43
+ }
44
+ }
45
+ ```
46
+
47
+ ## Tools
48
+
49
+ ### `lu_load_protocol`
50
+
51
+ Parse a `.lu` protocol definition and extract its structure.
52
+
53
+ ### `lu_verify_message`
54
+
55
+ Check if a message is valid in the context of an ongoing session.
56
+
57
+ ### `lu_check_properties`
58
+
59
+ Verify formal safety properties (always terminates, no deadlock, etc.).
60
+
61
+ ### `lu_list_templates`
62
+
63
+ Browse 20 standard library protocols across 5 categories.
64
+
65
+ ## Example
66
+
67
+ ```
68
+ protocol OrderProcessing:
69
+ roles: customer, warehouse, payment
70
+ customer asks warehouse to check availability
71
+ warehouse returns stock status to customer
72
+ when customer decides:
73
+ in_stock:
74
+ customer asks payment to process order
75
+ payment returns confirmation to customer
76
+ out_of_stock:
77
+ customer sends cancellation to warehouse
78
+ properties:
79
+ always terminates
80
+ no deadlock
81
+ all roles participate
82
+ ```
83
+
84
+ ## Links
85
+
86
+ - [Playground](https://rafapra3008.github.io/cervellaswarm/) -- try LU in your browser
87
+ - [PyPI](https://pypi.org/project/cervellaswarm-lingua-universale/) -- core package
88
+ - [VS Code](https://marketplace.visualstudio.com/items?itemName=cervellaswarm.lingua-universale) -- editor extension
89
+
90
+ ## License
91
+
92
+ Apache 2.0
@@ -0,0 +1,647 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 CervellaSwarm Contributors
4
+
5
+ """Lingua Universale MCP Server.
6
+
7
+ Exposes Lingua Universale protocol verification as MCP tools for
8
+ Claude Code, Cursor, Windsurf, and any MCP-compatible client.
9
+
10
+ Four tools:
11
+ - lu_load_protocol -- parse a .lu source file
12
+ - lu_verify_message -- check if a message is valid in session context
13
+ - lu_check_properties -- verify formal safety properties
14
+ - lu_list_templates -- browse the standard library (20 protocols)
15
+
16
+ Usage:
17
+ pip install lu-mcp-server
18
+ lu-mcp-server # stdio transport (default)
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import logging
25
+ from importlib.metadata import version, PackageNotFoundError
26
+ from typing import Any
27
+
28
+ try:
29
+ __version__ = version("lu-mcp-server")
30
+ except PackageNotFoundError:
31
+ __version__ = "0.1.0"
32
+
33
+ from mcp.server.fastmcp import FastMCP
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ mcp = FastMCP(
38
+ "lingua-universale",
39
+ instructions=(
40
+ "Verify agent-to-agent communication against session type protocols. "
41
+ "Mathematical proofs, not trust. "
42
+ "Use lu_load_protocol to parse a .lu definition, "
43
+ "lu_verify_message to check individual messages, "
44
+ "lu_check_properties for formal safety proofs, "
45
+ "and lu_list_templates to browse 20 standard library protocols."
46
+ ),
47
+ )
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Helper: import LU with a clear error if not installed
52
+ # ---------------------------------------------------------------------------
53
+
54
+
55
+ def _require_lu() -> Any:
56
+ """Return the cervellaswarm_lingua_universale module or raise ImportError."""
57
+ try:
58
+ import cervellaswarm_lingua_universale as lu # noqa: PLC0415
59
+ return lu
60
+ except ImportError as exc:
61
+ raise ImportError(
62
+ "cervellaswarm-lingua-universale is not installed. "
63
+ "Run: pip install cervellaswarm-lingua-universale>=0.3.3"
64
+ ) from exc
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Tool 1: lu_load_protocol
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ @mcp.tool()
73
+ async def lu_load_protocol(protocol_text: str) -> str:
74
+ """Parse a Lingua Universale (.lu) protocol definition.
75
+
76
+ Accepts the full text of a .lu file and returns the parsed protocol
77
+ structure: name, roles, steps, choices, and declared properties.
78
+
79
+ Args:
80
+ protocol_text: Content of a .lu file, e.g.:
81
+ "protocol RequestResponse:\\n"
82
+ " roles: client, server\\n"
83
+ " client asks server to process request\\n"
84
+ " server returns response to client\\n"
85
+ " properties:\\n"
86
+ " always terminates\\n"
87
+ " no deadlock\\n"
88
+
89
+ Returns:
90
+ JSON string with keys:
91
+ ok (bool), protocol_name (str), roles (list[str]),
92
+ steps (list), properties (list), error (str on failure).
93
+ """
94
+ lu = _require_lu()
95
+
96
+ result = lu.check_source(protocol_text, source_file="<mcp-input>")
97
+
98
+ if not result.ok:
99
+ return json.dumps({
100
+ "ok": False,
101
+ "error": "; ".join(result.errors),
102
+ })
103
+
104
+ # Extract protocol info from the compiled module's AST via verify_source
105
+ # (check_source only compiles; verify_source also walks declarations)
106
+ verify_result = lu.verify_source(protocol_text, source_file="<mcp-input>")
107
+
108
+ protocols_info: list[dict[str, Any]] = []
109
+
110
+ # Walk property reports to extract protocol metadata
111
+ for report in verify_result.property_reports:
112
+ protocol_name = report.protocol_name
113
+ props: list[dict[str, Any]] = []
114
+ for pr in report.results:
115
+ props.append({
116
+ "kind": pr.spec.kind.value,
117
+ "verdict": pr.verdict.value,
118
+ "evidence": pr.evidence,
119
+ "params": list(pr.spec.params),
120
+ })
121
+ protocols_info.append({
122
+ "protocol_name": protocol_name,
123
+ "properties": props,
124
+ "all_passed": report.all_passed,
125
+ "passed_count": report.passed_count,
126
+ "violated_count": report.violated_count,
127
+ })
128
+
129
+ # Also extract parse-level info via the _parser + _ast
130
+ from cervellaswarm_lingua_universale._parser import parse # noqa: PLC0415
131
+ from cervellaswarm_lingua_universale._ast import ( # noqa: PLC0415
132
+ ProtocolNode,
133
+ AgentNode,
134
+ ChoiceNode,
135
+ )
136
+
137
+ try:
138
+ program = parse(protocol_text)
139
+ except Exception as exc:
140
+ logger.warning("Parse error in lu_load_protocol: %s", exc)
141
+ return json.dumps({
142
+ "ok": False,
143
+ "error": f"Parse error: {exc}",
144
+ })
145
+
146
+ protocols_detail: list[dict[str, Any]] = []
147
+ agents_detail: list[dict[str, Any]] = []
148
+
149
+ for decl in program.declarations:
150
+ if isinstance(decl, ProtocolNode):
151
+ steps_info = _steps_to_list(decl.steps)
152
+ protocols_detail.append({
153
+ "name": decl.name,
154
+ "roles": list(decl.roles),
155
+ "steps": steps_info,
156
+ "step_count": len(steps_info),
157
+ "has_choices": any(
158
+ isinstance(s, ChoiceNode) for s in decl.steps
159
+ ),
160
+ })
161
+ elif isinstance(decl, AgentNode):
162
+ agents_detail.append({
163
+ "name": decl.name,
164
+ "role": decl.role,
165
+ "trust": decl.trust,
166
+ })
167
+
168
+ return json.dumps({
169
+ "ok": True,
170
+ "protocols": protocols_detail,
171
+ "agents": agents_detail,
172
+ "property_reports": protocols_info,
173
+ "summary": {
174
+ "protocol_count": len(protocols_detail),
175
+ "agent_count": len(agents_detail),
176
+ },
177
+ }, indent=2)
178
+
179
+
180
+ def _steps_to_list(steps: list[Any]) -> list[dict[str, Any]]:
181
+ """Recursively convert AST step/choice nodes to serialisable dicts."""
182
+ from cervellaswarm_lingua_universale._ast import ChoiceNode # noqa: PLC0415
183
+
184
+ result: list[dict[str, Any]] = []
185
+ for step in steps:
186
+ if isinstance(step, ChoiceNode):
187
+ branches: dict[str, list[dict[str, Any]]] = {}
188
+ for branch in step.branches:
189
+ branches[branch.label] = _steps_to_list(branch.steps)
190
+ result.append({
191
+ "type": "choice",
192
+ "decider": step.decider,
193
+ "branches": branches,
194
+ })
195
+ elif hasattr(step, "sender"):
196
+ result.append({
197
+ "type": "step",
198
+ "sender": step.sender,
199
+ "receiver": step.receiver,
200
+ "action": step.action,
201
+ "payload": getattr(step, "payload", ""),
202
+ })
203
+ return result
204
+
205
+
206
+ # ---------------------------------------------------------------------------
207
+ # Tool 2: lu_verify_message
208
+ # ---------------------------------------------------------------------------
209
+
210
+
211
+ @mcp.tool()
212
+ async def lu_verify_message(
213
+ protocol_text: str,
214
+ messages: list[dict[str, str]],
215
+ next_message: dict[str, str],
216
+ ) -> str:
217
+ """Verify whether a message is valid in the context of an ongoing session.
218
+
219
+ Replays the existing message history against the protocol, then checks
220
+ whether next_message is the expected next step.
221
+
222
+ Args:
223
+ protocol_text: Full .lu protocol definition text.
224
+ messages: List of already-sent messages, each a dict with keys:
225
+ sender (str), receiver (str), action (str).
226
+ Actions are LU action names: "asks", "returns", "sends",
227
+ "proposes", "tells". These match the verbs in .lu source files.
228
+ next_message: The message to validate, same format as above.
229
+
230
+ Returns:
231
+ JSON string:
232
+ On success: {"valid": true, "step": N, "next_expected": "..."}
233
+ On violation: {"valid": false, "violation": "...", "expected": "...", "got": "..."}
234
+ On error: {"valid": false, "error": "..."}
235
+
236
+ Example:
237
+ protocol_text = "protocol Ping:\\n roles: a, b\\n a asks b to ping\\n b returns pong to a\\n properties:\\n always terminates\\n"
238
+ messages = [{"sender": "a", "receiver": "b", "action": "ask"}]
239
+ next_message = {"sender": "b", "receiver": "a", "action": "return"}
240
+ # Returns: {"valid": true, ...}
241
+ """
242
+ lu = _require_lu()
243
+
244
+ # Step 1: Parse the protocol
245
+ from cervellaswarm_lingua_universale._parser import parse # noqa: PLC0415
246
+ from cervellaswarm_lingua_universale._eval import _protocol_node_to_runtime # noqa: PLC0415
247
+ from cervellaswarm_lingua_universale._ast import ProtocolNode # noqa: PLC0415
248
+
249
+ try:
250
+ program = parse(protocol_text)
251
+ except Exception as exc:
252
+ logger.warning("Parse error in lu_verify_message: %s", exc)
253
+ return json.dumps({"valid": False, "error": f"Parse error: {exc}"})
254
+
255
+ protocol_nodes = [
256
+ d for d in program.declarations if isinstance(d, ProtocolNode)
257
+ ]
258
+ if not protocol_nodes:
259
+ return json.dumps({
260
+ "valid": False,
261
+ "error": "No protocol declaration found in protocol_text.",
262
+ })
263
+
264
+ # Use first protocol (most common case)
265
+ protocol_obj = _protocol_node_to_runtime(protocol_nodes[0])
266
+
267
+ # Step 2: Build a SessionChecker and replay history
268
+ checker = lu.SessionChecker(protocol_obj, session_id="mcp-verify")
269
+
270
+ # Map action names to MessageKind via the action->kind table from _eval
271
+ from cervellaswarm_lingua_universale._eval import _action_to_kind_map # noqa: PLC0415
272
+
273
+ action_map = _action_to_kind_map()
274
+
275
+ def _make_swarm_msg(action: str) -> Any:
276
+ """Create a minimal SwarmMessage for the given action."""
277
+ from cervellaswarm_lingua_universale.types import ( # noqa: PLC0415
278
+ TaskRequest, MessageKind,
279
+ )
280
+
281
+ kind = action_map.get(action.lower())
282
+ if kind is None:
283
+ # Fallback: try direct MessageKind value lookup
284
+ for mk in MessageKind:
285
+ if mk.value == action.lower():
286
+ kind = mk
287
+ break
288
+ if kind is None:
289
+ raise ValueError(
290
+ f"Unknown action '{action}'. "
291
+ f"Known actions: {sorted(action_map.keys())}"
292
+ )
293
+ # Return the simplest valid SwarmMessage for this kind
294
+ return _kind_to_swarm_msg(kind)
295
+
296
+ # Replay existing messages
297
+ for i, msg in enumerate(messages):
298
+ sender = msg.get("sender", "")
299
+ receiver = msg.get("receiver", "")
300
+ action = msg.get("action", "")
301
+
302
+ try:
303
+ swarm_msg = _make_swarm_msg(action)
304
+ except ValueError as exc:
305
+ return json.dumps({
306
+ "valid": False,
307
+ "error": f"Message {i}: {exc}",
308
+ })
309
+
310
+ try:
311
+ checker.send(sender, receiver, swarm_msg)
312
+ except lu.ProtocolViolation as exc:
313
+ return json.dumps({
314
+ "valid": False,
315
+ "error": f"History replay failed at message {i}: {exc}",
316
+ "expected": exc.expected,
317
+ "got": exc.got,
318
+ })
319
+ except lu.SessionComplete as exc:
320
+ return json.dumps({
321
+ "valid": False,
322
+ "error": f"Protocol already complete at message {i}: {exc}",
323
+ })
324
+
325
+ # Step 3: Check the next message
326
+ next_sender = next_message.get("sender", "")
327
+ next_receiver = next_message.get("receiver", "")
328
+ next_action = next_message.get("action", "")
329
+
330
+ try:
331
+ next_swarm_msg = _make_swarm_msg(next_action)
332
+ except ValueError as exc:
333
+ return json.dumps({"valid": False, "error": str(exc)})
334
+
335
+ # Peek at what's expected before attempting send
336
+ # NOTE: uses private API (_state) -- no public equivalent yet
337
+ try:
338
+ expected_step = checker._state.peek_next_step()
339
+ except AttributeError:
340
+ expected_step = None
341
+ expected_desc = (
342
+ f"{expected_step.sender} -> {expected_step.receiver} : {expected_step.message_kind.value}"
343
+ if expected_step else "protocol complete or at choice point"
344
+ )
345
+
346
+ try:
347
+ checker.send(next_sender, next_receiver, next_swarm_msg)
348
+ except lu.ProtocolViolation as exc:
349
+ return json.dumps({
350
+ "valid": False,
351
+ "violation": str(exc),
352
+ "expected": exc.expected,
353
+ "got": exc.got,
354
+ "step": exc.step,
355
+ })
356
+ except lu.SessionComplete as exc:
357
+ return json.dumps({
358
+ "valid": False,
359
+ "violation": str(exc),
360
+ "expected": "no more messages (protocol complete)",
361
+ "got": f"{next_sender} -> {next_receiver} : {next_action}",
362
+ })
363
+
364
+ # Success
365
+ # NOTE: uses private API (_state) -- no public equivalent yet
366
+ try:
367
+ next_expected_step = checker._state.peek_next_step()
368
+ except AttributeError:
369
+ next_expected_step = None
370
+ next_expected_desc = (
371
+ f"{next_expected_step.sender} -> {next_expected_step.receiver} : {next_expected_step.message_kind.value}"
372
+ if next_expected_step else "protocol complete"
373
+ )
374
+
375
+ return json.dumps({
376
+ "valid": True,
377
+ "step": checker.step_index,
378
+ "is_complete": checker.is_complete,
379
+ "next_expected": next_expected_desc,
380
+ })
381
+
382
+
383
+ def _kind_to_swarm_msg(kind: Any) -> Any:
384
+ """Return the simplest valid SwarmMessage for a given MessageKind."""
385
+ from cervellaswarm_lingua_universale.types import ( # noqa: PLC0415
386
+ MessageKind,
387
+ TaskRequest,
388
+ TaskResult,
389
+ AuditRequest,
390
+ AuditVerdict,
391
+ PlanRequest,
392
+ PlanProposal,
393
+ PlanDecision,
394
+ ResearchQuery,
395
+ ResearchReport,
396
+ DirectMessage,
397
+ Broadcast,
398
+ ShutdownRequest,
399
+ ShutdownAck,
400
+ ContextInject,
401
+ AuditVerdictType,
402
+ PlanComplexity,
403
+ TaskStatus,
404
+ )
405
+
406
+ _KIND_TO_MSG: dict[MessageKind, Any] = {
407
+ MessageKind.TASK_REQUEST: TaskRequest(
408
+ task_id="mcp-t1", description="verify",
409
+ ),
410
+ MessageKind.TASK_RESULT: TaskResult(
411
+ task_id="mcp-t1", status=TaskStatus.OK, summary="ok",
412
+ ),
413
+ MessageKind.AUDIT_REQUEST: AuditRequest(
414
+ audit_id="mcp-a1", target="verify",
415
+ ),
416
+ MessageKind.AUDIT_VERDICT: AuditVerdict(
417
+ audit_id="mcp-a1", verdict=AuditVerdictType.APPROVED, score=9.5,
418
+ ),
419
+ MessageKind.PLAN_REQUEST: PlanRequest(
420
+ plan_id="mcp-p1", task_description="plan",
421
+ ),
422
+ MessageKind.PLAN_PROPOSAL: PlanProposal(
423
+ plan_id="mcp-p1", complexity=PlanComplexity.LOW,
424
+ risk_score=0.1, files_affected=1,
425
+ ),
426
+ MessageKind.PLAN_DECISION: PlanDecision(
427
+ plan_id="mcp-p1", approved=True,
428
+ ),
429
+ MessageKind.RESEARCH_QUERY: ResearchQuery(
430
+ query_id="mcp-q1", topic="verify",
431
+ ),
432
+ MessageKind.RESEARCH_REPORT: ResearchReport(
433
+ query_id="mcp-q1", topic="verify", sources_consulted=1,
434
+ ),
435
+ MessageKind.DM: DirectMessage(
436
+ sender_role="mcp", content="verify",
437
+ ),
438
+ MessageKind.BROADCAST: Broadcast(
439
+ sender_role="mcp", content="verify",
440
+ ),
441
+ MessageKind.SHUTDOWN_REQUEST: ShutdownRequest(
442
+ target_role="mcp",
443
+ ),
444
+ MessageKind.SHUTDOWN_ACK: ShutdownAck(
445
+ target_role="mcp",
446
+ ),
447
+ MessageKind.CONTEXT_INJECT: ContextInject(
448
+ context_type="mcp", content="verify",
449
+ ),
450
+ }
451
+
452
+ msg = _KIND_TO_MSG.get(kind)
453
+ if msg is None:
454
+ # Fallback for any unknown kind: use DirectMessage
455
+ msg = DirectMessage(sender_role="mcp", content=f"mcp-verify-{kind.value}")
456
+ return msg
457
+
458
+
459
+ # ---------------------------------------------------------------------------
460
+ # Tool 3: lu_check_properties
461
+ # ---------------------------------------------------------------------------
462
+
463
+
464
+ @mcp.tool()
465
+ async def lu_check_properties(protocol_text: str) -> str:
466
+ """Verify the formal safety properties declared in a .lu protocol.
467
+
468
+ Runs the static property checker (Layer 1) on all protocols found in
469
+ the source. Optionally, if Lean 4 is installed, also runs formal
470
+ verification (Layer 2).
471
+
472
+ Args:
473
+ protocol_text: Full .lu protocol definition text including a
474
+ "properties:" block, e.g.:
475
+ " properties:\\n"
476
+ " always terminates\\n"
477
+ " no deadlock\\n"
478
+ " all roles participate\\n"
479
+
480
+ Returns:
481
+ JSON string with:
482
+ ok (bool), protocols (list of protocol results), summary (dict).
483
+ Each protocol result has: protocol_name, all_passed, results (list).
484
+ Each result has: kind, verdict, evidence, params.
485
+ """
486
+ lu = _require_lu()
487
+
488
+ verify_result = lu.verify_source(protocol_text, source_file="<mcp-input>")
489
+
490
+ if not verify_result.ok and not verify_result.property_reports:
491
+ return json.dumps({
492
+ "ok": False,
493
+ "error": "; ".join(verify_result.errors),
494
+ })
495
+
496
+ protocols_out: list[dict[str, Any]] = []
497
+
498
+ for report in verify_result.property_reports:
499
+ results_out: list[dict[str, Any]] = []
500
+ for pr in report.results:
501
+ results_out.append({
502
+ "kind": pr.spec.kind.value,
503
+ "verdict": pr.verdict.value,
504
+ "evidence": pr.evidence,
505
+ "params": list(pr.spec.params),
506
+ "threshold": pr.spec.threshold if pr.spec.threshold is not None and pr.spec.threshold != 0.0 else None,
507
+ })
508
+
509
+ protocols_out.append({
510
+ "protocol_name": report.protocol_name,
511
+ "all_passed": report.all_passed,
512
+ "passed_count": report.passed_count,
513
+ "violated_count": report.violated_count,
514
+ "results": results_out,
515
+ })
516
+
517
+ # Include Lean 4 lines if available
518
+ lean4_lines = verify_result.verification
519
+
520
+ total_passed = sum(p["passed_count"] for p in protocols_out)
521
+ total_violated = sum(p["violated_count"] for p in protocols_out)
522
+
523
+ return json.dumps({
524
+ "ok": verify_result.ok,
525
+ "protocols": protocols_out,
526
+ "lean4_output": lean4_lines,
527
+ "summary": {
528
+ "protocol_count": len(protocols_out),
529
+ "total_passed": total_passed,
530
+ "total_violated": total_violated,
531
+ "parse_errors": verify_result.errors,
532
+ },
533
+ }, indent=2)
534
+
535
+
536
+ # ---------------------------------------------------------------------------
537
+ # Tool 4: lu_list_templates
538
+ # ---------------------------------------------------------------------------
539
+
540
+
541
+ @mcp.tool()
542
+ async def lu_list_templates(category: str = "") -> str:
543
+ """List available Lingua Universale standard library protocol templates.
544
+
545
+ The standard library contains 20 verified protocols across 5 categories:
546
+ communication, data, business, ai_ml, security.
547
+
548
+ Args:
549
+ category: Optional filter. One of: communication, data, business,
550
+ ai_ml, security. Leave empty to list all templates.
551
+
552
+ Returns:
553
+ JSON string with:
554
+ ok (bool), templates (list), category_filter (str), total (int).
555
+ Each template has: name, category, description.
556
+ """
557
+ from pathlib import Path # noqa: PLC0415
558
+
559
+ try:
560
+ from cervellaswarm_lingua_universale._init_project import ( # noqa: PLC0415
561
+ list_templates,
562
+ _STDLIB_DIR,
563
+ )
564
+ except ImportError as exc:
565
+ return json.dumps({"ok": False, "error": str(exc)})
566
+
567
+ # Category descriptions for context
568
+ _CATEGORY_DESCRIPTIONS: dict[str, str] = {
569
+ "communication": "Fundamental messaging patterns (request/response, pub/sub, scatter/gather)",
570
+ "data": "Data management protocols (CRUD, sync, cache invalidation)",
571
+ "business": "Business workflow patterns (approval, auction, saga, two-buyer)",
572
+ "ai_ml": "AI/ML agent protocols (RAG, delegation, tool calling, human-in-loop, consensus)",
573
+ "security": "Security protocols (auth handshake, mutual TLS, rate limiting)",
574
+ }
575
+
576
+ # Property highlights per template (hand-curated from stdlib README)
577
+ _TEMPLATE_HIGHLIGHTS: dict[str, str] = {
578
+ "request_response": "always terminates, no deadlock",
579
+ "ping_pong": "always terminates, no deadlock",
580
+ "pub_sub": "all roles participate",
581
+ "scatter_gather": "all roles participate",
582
+ "pipeline": "ordering (source -> processor -> transformer -> sink)",
583
+ "crud_safe": "no deletion, all roles participate",
584
+ "data_sync": "ordering (primary before replica)",
585
+ "cache_invalidation": "choice (hit/miss), all roles participate",
586
+ "two_buyer": "MPST canonical (Honda/Yoshida POPL 2008)",
587
+ "approval_workflow": "role exclusive (only approver decides)",
588
+ "auction": "choice (sold/unsold)",
589
+ "saga_order": "distributed transaction, ordering",
590
+ "rag_pipeline": "ordering (retrieval before generation)",
591
+ "agent_delegation": "trust >= standard, ordering",
592
+ "tool_calling": "ordering (registry before executor)",
593
+ "human_in_loop": "role exclusive (only human decides)",
594
+ "consensus": "all roles participate, confidence >= medium",
595
+ "auth_handshake": "ordering, exclusion (client cannot send token)",
596
+ "mutual_tls": "all roles participate, ordering",
597
+ "rate_limited_api": "role exclusive (only limiter throttles)",
598
+ }
599
+
600
+ all_names = list_templates()
601
+
602
+ templates: list[dict[str, str]] = []
603
+ for name in all_names:
604
+ # Determine category from path
605
+ cat = ""
606
+ for category_dir in _STDLIB_DIR.iterdir():
607
+ if category_dir.is_dir():
608
+ if (category_dir / f"{name}.lu").exists():
609
+ cat = category_dir.name
610
+ break
611
+
612
+ # Apply filter if provided
613
+ if category and cat != category:
614
+ continue
615
+
616
+ templates.append({
617
+ "name": name,
618
+ "category": cat,
619
+ "description": _TEMPLATE_HIGHLIGHTS.get(name, ""),
620
+ "usage": f"lu init my-project --template {name}",
621
+ })
622
+
623
+ categories_present = sorted({t["category"] for t in templates})
624
+
625
+ return json.dumps({
626
+ "ok": True,
627
+ "templates": templates,
628
+ "category_filter": category or "all",
629
+ "total": len(templates),
630
+ "categories": {
631
+ c: _CATEGORY_DESCRIPTIONS.get(c, c) for c in categories_present
632
+ },
633
+ }, indent=2)
634
+
635
+
636
+ # ---------------------------------------------------------------------------
637
+ # Entrypoint
638
+ # ---------------------------------------------------------------------------
639
+
640
+
641
+ def main() -> None:
642
+ """Run the MCP server (stdio transport)."""
643
+ mcp.run()
644
+
645
+
646
+ if __name__ == "__main__":
647
+ main()
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lu-mcp-server"
7
+ version = "0.1.0"
8
+ description = "MCP server for Lingua Universale protocol verification -- verify AI agent communication with session types"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "CervellaSwarm", email = "noreply@cervellaswarm.com"}]
13
+ keywords = ["mcp", "session-types", "protocol-verification", "ai-agents", "formal-methods"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: Software Development :: Quality Assurance",
21
+ ]
22
+ dependencies = [
23
+ "cervellaswarm-lingua-universale>=0.3.3",
24
+ "mcp[cli]>=1.0.0",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest>=7.0"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/rafapra3008/cervellaswarm"
32
+ Documentation = "https://rafapra3008.github.io/cervellaswarm/"
33
+ Repository = "https://github.com/rafapra3008/cervellaswarm"
34
+ Issues = "https://github.com/rafapra3008/cervellaswarm/issues"
35
+
36
+ [project.scripts]
37
+ lu-mcp-server = "lu_mcp_server:main"
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
@@ -0,0 +1,147 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Smoke tests for lu-mcp-server."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+
8
+
9
+ def test_import():
10
+ """Module imports without error."""
11
+ import lu_mcp_server # noqa: F401
12
+
13
+
14
+ def test_version():
15
+ """Package exposes __version__."""
16
+ from lu_mcp_server import __version__
17
+ assert isinstance(__version__, str)
18
+ assert "." in __version__
19
+
20
+
21
+ def test_main_exists():
22
+ """Entry point function exists."""
23
+ from lu_mcp_server import main
24
+ assert callable(main)
25
+
26
+
27
+ def test_mcp_server_instance():
28
+ """FastMCP server is created with correct name."""
29
+ from lu_mcp_server import mcp
30
+ assert mcp.name == "lingua-universale"
31
+
32
+
33
+ def test_require_lu():
34
+ """Helper returns the LU module."""
35
+ from lu_mcp_server import _require_lu
36
+ lu = _require_lu()
37
+ assert hasattr(lu, "check_source")
38
+ assert hasattr(lu, "SessionChecker")
39
+
40
+
41
+ def test_steps_to_list_empty():
42
+ """Empty step list returns empty list."""
43
+ from lu_mcp_server import _steps_to_list
44
+ assert _steps_to_list([]) == []
45
+
46
+
47
+ def test_tool_lu_load_protocol():
48
+ """lu_load_protocol parses a simple protocol."""
49
+ import asyncio
50
+ from lu_mcp_server import lu_load_protocol
51
+
52
+ protocol = (
53
+ "protocol Ping:\n"
54
+ " roles: a, b\n"
55
+ " a asks b to ping\n"
56
+ " b returns pong to a\n"
57
+ " properties:\n"
58
+ " always terminates\n"
59
+ )
60
+ result = json.loads(asyncio.run(lu_load_protocol(protocol)))
61
+ assert result["ok"] is True
62
+ assert result["protocols"][0]["name"] == "Ping"
63
+ assert len(result["protocols"][0]["roles"]) == 2
64
+
65
+
66
+ def test_tool_lu_check_properties():
67
+ """lu_check_properties verifies safety properties."""
68
+ import asyncio
69
+ from lu_mcp_server import lu_check_properties
70
+
71
+ protocol = (
72
+ "protocol Safe:\n"
73
+ " roles: x, y\n"
74
+ " x asks y to do thing\n"
75
+ " y returns result to x\n"
76
+ " properties:\n"
77
+ " always terminates\n"
78
+ " no deadlock\n"
79
+ )
80
+ result = json.loads(asyncio.run(lu_check_properties(protocol)))
81
+ assert result["ok"] is True
82
+ assert result["summary"]["total_violated"] == 0
83
+
84
+
85
+ def test_tool_lu_list_templates():
86
+ """lu_list_templates returns standard library templates."""
87
+ import asyncio
88
+ from lu_mcp_server import lu_list_templates
89
+
90
+ result = json.loads(asyncio.run(lu_list_templates()))
91
+ assert result["ok"] is True
92
+ assert result["total"] == 20
93
+
94
+
95
+ def test_tool_lu_list_templates_filtered():
96
+ """lu_list_templates filters by category."""
97
+ import asyncio
98
+ from lu_mcp_server import lu_list_templates
99
+
100
+ result = json.loads(asyncio.run(lu_list_templates(category="security")))
101
+ assert result["ok"] is True
102
+ assert result["total"] == 3
103
+ assert all(t["category"] == "security" for t in result["templates"])
104
+
105
+
106
+ def test_tool_lu_verify_message_invalid_action():
107
+ """lu_verify_message returns error for unknown action."""
108
+ import asyncio
109
+ from lu_mcp_server import lu_verify_message
110
+
111
+ protocol = (
112
+ "protocol PingPong:\n"
113
+ " roles: a, b\n"
114
+ " a asks b to ping\n"
115
+ " b returns pong to a\n"
116
+ " properties:\n"
117
+ " always terminates\n"
118
+ )
119
+ result = json.loads(asyncio.run(lu_verify_message(
120
+ protocol_text=protocol,
121
+ messages=[],
122
+ next_message={"sender": "a", "receiver": "b", "action": "invalid"},
123
+ )))
124
+ assert result["valid"] is False
125
+ assert "error" in result
126
+
127
+
128
+ def test_tool_lu_verify_message_no_protocol():
129
+ """lu_verify_message returns error when no protocol found."""
130
+ import asyncio
131
+ from lu_mcp_server import lu_verify_message
132
+
133
+ result = json.loads(asyncio.run(lu_verify_message(
134
+ protocol_text="not a protocol",
135
+ messages=[],
136
+ next_message={"sender": "a", "receiver": "b", "action": "asks"},
137
+ )))
138
+ assert result["valid"] is False
139
+
140
+
141
+ def test_tool_lu_load_protocol_invalid():
142
+ """lu_load_protocol returns error for invalid input."""
143
+ import asyncio
144
+ from lu_mcp_server import lu_load_protocol
145
+
146
+ result = json.loads(asyncio.run(lu_load_protocol("not a protocol")))
147
+ assert result["ok"] is False