moltlang 0.1.0__py3-none-any.whl

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.
mcp_server/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ MoltLang MCP Server.
3
+
4
+ This module provides a Model Context Protocol (MCP) server for MoltLang,
5
+ enabling AI agents to translate between human languages and MoltLang.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from mcp_server.server import MCPServer
11
+ from mcp_server.endpoints import MCPEndpoints
12
+
13
+ __all__ = ["MCPServer", "MCPEndpoints"]
@@ -0,0 +1,177 @@
1
+ """
2
+ MoltLang MCP API endpoints.
3
+
4
+ This module provides the HTTP/WebSocket endpoints for the MoltLang MCP server.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+ from typing import Any
10
+
11
+
12
+ class EndpointType(Enum):
13
+ """Types of MCP endpoints."""
14
+
15
+ TRANSLATE = "translate"
16
+ VALIDATE = "validate"
17
+ VOCABULARY = "vocabulary"
18
+ HEALTH = "health"
19
+
20
+
21
+ @dataclass
22
+ class EndpointResponse:
23
+ """
24
+ Response from an MCP endpoint.
25
+
26
+ Attributes:
27
+ success: Whether the request was successful
28
+ data: Response data
29
+ error: Error message if unsuccessful
30
+ metadata: Optional metadata about the response
31
+ """
32
+
33
+ success: bool
34
+ data: dict[str, Any] | None = None
35
+ error: str | None = None
36
+ metadata: dict[str, Any] = None
37
+
38
+ def to_dict(self) -> dict[str, Any]:
39
+ """Convert to dictionary for JSON serialization."""
40
+ result = {"success": self.success}
41
+ if self.data is not None:
42
+ result["data"] = self.data
43
+ if self.error is not None:
44
+ result["error"] = self.error
45
+ if self.metadata is not None:
46
+ result["metadata"] = self.metadata
47
+ return result
48
+
49
+
50
+ class MCPEndpoints:
51
+ """
52
+ MoltLang MCP endpoints.
53
+
54
+ Provides HTTP/WebSocket endpoints for MoltLang translation services.
55
+ """
56
+
57
+ def __init__(self):
58
+ """Initialize the MCP endpoints."""
59
+ from moltlang import MoltTranslator, MoltValidator
60
+
61
+ self.translator = MoltTranslator()
62
+ self.validator = MoltValidator()
63
+
64
+ async def translate(
65
+ self, text: str, to_molt: bool = True, target_language: str = "en"
66
+ ) -> EndpointResponse:
67
+ """
68
+ Translate between human language and MoltLang.
69
+
70
+ Args:
71
+ text: Text to translate
72
+ to_molt: True for human -> MoltLang, False for MoltLang -> human
73
+ target_language: Target language code
74
+
75
+ Returns:
76
+ EndpointResponse with translation result
77
+ """
78
+ try:
79
+ if to_molt:
80
+ result = self.translator.translate_to_molt(text)
81
+ data = {
82
+ "moltlang": result.text,
83
+ "token_count": result.token_count,
84
+ "original_token_count": result.original_token_count,
85
+ "efficiency": result.token_efficiency,
86
+ "confidence": result.confidence,
87
+ }
88
+ else:
89
+ result = self.translator.translate_from_molt(text)
90
+ data = {
91
+ "translation": result.text,
92
+ "token_count": result.token_count,
93
+ "confidence": result.confidence,
94
+ }
95
+
96
+ return EndpointResponse(success=True, data=data)
97
+ except Exception as e:
98
+ return EndpointResponse(success=False, error=str(e))
99
+
100
+ async def validate(self, original: str, translated: str) -> EndpointResponse:
101
+ """
102
+ Validate a translation.
103
+
104
+ Args:
105
+ original: Original text
106
+ translated: Translated text
107
+
108
+ Returns:
109
+ EndpointResponse with validation result
110
+ """
111
+ try:
112
+ quality = self.validator.validate_translation(original, translated)
113
+ data = {
114
+ "is_valid": quality.is_valid,
115
+ "score": quality.score,
116
+ "token_efficiency": quality.token_efficiency,
117
+ "confidence": quality.confidence,
118
+ "issues": [
119
+ {
120
+ "type": issue.type.value,
121
+ "message": issue.message,
122
+ "severity": issue.severity,
123
+ }
124
+ for issue in quality.issues
125
+ ],
126
+ "metrics": quality.metrics,
127
+ }
128
+ return EndpointResponse(success=True, data=data)
129
+ except Exception as e:
130
+ return EndpointResponse(success=False, error=str(e))
131
+
132
+ async def vocabulary(self, token_type: str | None = None) -> EndpointResponse:
133
+ """
134
+ List MoltLang vocabulary/tokens.
135
+
136
+ Args:
137
+ token_type: Optional token type filter
138
+
139
+ Returns:
140
+ EndpointResponse with token list
141
+ """
142
+ try:
143
+ from moltlang.tokens import TokenType, TokenRegistry
144
+
145
+ registry = TokenRegistry()
146
+
147
+ if token_type:
148
+ token_type_prefix = token_type.upper()
149
+ tokens = [t for t in TokenType if t.name.startswith(token_type_prefix)]
150
+ else:
151
+ tokens = list(TokenType)
152
+
153
+ data = {
154
+ "tokens": [{"name": t.name, "value": t.value} for t in tokens],
155
+ "count": len(tokens),
156
+ "filtered_by": token_type,
157
+ }
158
+ return EndpointResponse(success=True, data=data)
159
+ except Exception as e:
160
+ return EndpointResponse(success=False, error=str(e))
161
+
162
+ async def health(self) -> EndpointResponse:
163
+ """
164
+ Health check endpoint.
165
+
166
+ Returns:
167
+ EndpointResponse with health status
168
+ """
169
+ data = {
170
+ "status": "healthy",
171
+ "version": "0.1.0",
172
+ "services": {
173
+ "translator": "ok",
174
+ "validator": "ok",
175
+ },
176
+ }
177
+ return EndpointResponse(success=True, data=data)
mcp_server/server.py ADDED
@@ -0,0 +1,303 @@
1
+ """
2
+ MoltLang MCP Server implementation.
3
+
4
+ This module implements the Model Context Protocol server for MoltLang translation.
5
+ """
6
+
7
+ import asyncio
8
+ import json
9
+ from typing import Any
10
+
11
+ from mcp.server.models import InitializationOptions
12
+ from mcp.server.sse import SseServerTransport
13
+ from mcp.server.stdio import stdio_server
14
+ from mcp.types import (
15
+ CallToolRequest,
16
+ CallToolResult,
17
+ ListToolsRequest,
18
+ ListToolsResult,
19
+ Tool,
20
+ TextContent,
21
+ ServerCapabilities,
22
+ )
23
+
24
+ from moltlang import MoltTranslator, MoltValidator, translate_to_molt, translate_from_molt, translate_to_molt_result, translate_from_molt_result
25
+
26
+
27
+ class MCPServer:
28
+ """
29
+ Model Context Protocol server for MoltLang.
30
+
31
+ Provides translation endpoints for AI agents to communicate using MoltLang.
32
+ """
33
+
34
+ def __init__(self):
35
+ """Initialize the MCP server."""
36
+ self.translator = MoltTranslator()
37
+ self.validator = MoltValidator()
38
+ self.tools = self._register_tools()
39
+
40
+ def _register_tools(self) -> list[Tool]:
41
+ """Register available MCP tools."""
42
+ return [
43
+ Tool(
44
+ name="translate_to_molt",
45
+ description="Translate human language text to MoltLang (AI-optimized language)",
46
+ inputSchema={
47
+ "type": "object",
48
+ "properties": {
49
+ "text": {
50
+ "type": "string",
51
+ "description": "Human language text to translate to MoltLang",
52
+ },
53
+ "target_language": {
54
+ "type": "string",
55
+ "description": "Source language code (default: 'en' for English)",
56
+ "default": "en",
57
+ },
58
+ },
59
+ "required": ["text"],
60
+ },
61
+ ),
62
+ Tool(
63
+ name="translate_from_molt",
64
+ description="Translate MoltLang to human language text",
65
+ inputSchema={
66
+ "type": "object",
67
+ "properties": {
68
+ "molt_text": {
69
+ "type": "string",
70
+ "description": "MoltLang text to translate to human language",
71
+ },
72
+ "target_language": {
73
+ "type": "string",
74
+ "description": "Target language code (default: 'en' for English)",
75
+ "default": "en",
76
+ },
77
+ },
78
+ "required": ["molt_text"],
79
+ },
80
+ ),
81
+ Tool(
82
+ name="validate_translation",
83
+ description="Validate a MoltLang translation and return quality metrics",
84
+ inputSchema={
85
+ "type": "object",
86
+ "properties": {
87
+ "original": {
88
+ "type": "string",
89
+ "description": "Original text before translation",
90
+ },
91
+ "translated": {
92
+ "type": "string",
93
+ "description": "Translated text to validate",
94
+ },
95
+ },
96
+ "required": ["original", "translated"],
97
+ },
98
+ ),
99
+ Tool(
100
+ name="list_tokens",
101
+ description="List all available MoltLang tokens, optionally filtered by type",
102
+ inputSchema={
103
+ "type": "object",
104
+ "properties": {
105
+ "token_type": {
106
+ "type": "string",
107
+ "description": "Filter by token type (e.g., 'OP', 'SRC', 'RET', 'PARAM')",
108
+ },
109
+ },
110
+ },
111
+ ),
112
+ Tool(
113
+ name="get_token_efficiency",
114
+ description="Calculate token efficiency for a translation",
115
+ inputSchema={
116
+ "type": "object",
117
+ "properties": {
118
+ "english_text": {
119
+ "type": "string",
120
+ "description": "English text to analyze",
121
+ },
122
+ "molt_text": {
123
+ "type": "string",
124
+ "description": "MoltLang translation to analyze",
125
+ },
126
+ },
127
+ "required": ["english_text", "molt_text"],
128
+ },
129
+ ),
130
+ ]
131
+
132
+ async def handle_translate_to_molt(self, arguments: dict[str, Any]) -> str:
133
+ """Handle translate_to_molt tool call."""
134
+ text = arguments.get("text", "")
135
+ if not text:
136
+ return json.dumps({"error": "Missing 'text' argument"})
137
+
138
+ result = self.translator.translate_to_molt(text)
139
+
140
+ return json.dumps(
141
+ {
142
+ "moltlang": result.text,
143
+ "token_count": result.token_count,
144
+ "original_token_count": result.original_token_count,
145
+ "efficiency": result.token_efficiency,
146
+ "confidence": result.confidence,
147
+ }
148
+ )
149
+
150
+ async def handle_translate_from_molt(self, arguments: dict[str, Any]) -> str:
151
+ """Handle translate_from_molt tool call."""
152
+ molt_text = arguments.get("molt_text", "")
153
+ if not molt_text:
154
+ return json.dumps({"error": "Missing 'molt_text' argument"})
155
+
156
+ result = self.translator.translate_from_molt(molt_text)
157
+
158
+ return json.dumps(
159
+ {
160
+ "translation": result.text,
161
+ "token_count": result.token_count,
162
+ "confidence": result.confidence,
163
+ }
164
+ )
165
+
166
+ async def handle_validate_translation(self, arguments: dict[str, Any]) -> str:
167
+ """Handle validate_translation tool call."""
168
+ original = arguments.get("original", "")
169
+ translated = arguments.get("translated", "")
170
+
171
+ if not original or not translated:
172
+ return json.dumps({"error": "Missing 'original' or 'translated' argument"})
173
+
174
+ quality = self.validator.validate_translation(original, translated)
175
+
176
+ return json.dumps(
177
+ {
178
+ "is_valid": quality.is_valid,
179
+ "score": quality.score,
180
+ "token_efficiency": quality.token_efficiency,
181
+ "confidence": quality.confidence,
182
+ "issues": [
183
+ {"type": issue.type.value, "message": issue.message, "severity": issue.severity}
184
+ for issue in quality.issues
185
+ ],
186
+ "metrics": quality.metrics,
187
+ }
188
+ )
189
+
190
+ async def handle_list_tokens(self, arguments: dict[str, Any]) -> str:
191
+ """Handle list_tokens tool call."""
192
+ from moltlang.tokens import TokenRegistry
193
+
194
+ registry = TokenRegistry()
195
+ token_type_filter = arguments.get("token_type")
196
+
197
+ # Note: This is a simplified implementation
198
+ # A full implementation would properly filter by token type
199
+
200
+ from moltlang.tokens import TokenType
201
+
202
+ if token_type_filter:
203
+ token_type_prefix = token_type_filter.upper()
204
+ tokens = [t for t in TokenType if t.name.startswith(token_type_prefix)]
205
+ else:
206
+ tokens = list(TokenType)
207
+
208
+ return json.dumps(
209
+ {"tokens": [{"name": t.name, "value": t.value} for t in tokens], "count": len(tokens)}
210
+ )
211
+
212
+ async def handle_get_token_efficiency(self, arguments: dict[str, Any]) -> str:
213
+ """Handle get_token_efficiency tool call."""
214
+ english_text = arguments.get("english_text", "")
215
+ molt_text = arguments.get("molt_text", "")
216
+
217
+ if not english_text or not molt_text:
218
+ return json.dumps({"error": "Missing 'english_text' or 'molt_text' argument"})
219
+
220
+ # Count tokens
221
+ english_tokens = len(english_text.split())
222
+ molt_tokens = molt_text.count("[") # Each token starts with [
223
+
224
+ efficiency = 1.0 - (molt_tokens / english_tokens) if english_tokens > 0 else 0.0
225
+
226
+ return json.dumps(
227
+ {
228
+ "english_tokens": english_tokens,
229
+ "molt_tokens": molt_tokens,
230
+ "efficiency": efficiency,
231
+ "reduction_percentage": efficiency * 100,
232
+ }
233
+ )
234
+
235
+ async def call_tool(self, request: CallToolRequest) -> CallToolResult:
236
+ """Handle a tool call request."""
237
+ tool_name = request.params.name
238
+ arguments = request.params.arguments or {}
239
+
240
+ try:
241
+ if tool_name == "translate_to_molt":
242
+ result = await self.handle_translate_to_molt(arguments)
243
+ elif tool_name == "translate_from_molt":
244
+ result = await self.handle_translate_from_molt(arguments)
245
+ elif tool_name == "validate_translation":
246
+ result = await self.handle_validate_translation(arguments)
247
+ elif tool_name == "list_tokens":
248
+ result = await self.handle_list_tokens(arguments)
249
+ elif tool_name == "get_token_efficiency":
250
+ result = await self.handle_get_token_efficiency(arguments)
251
+ else:
252
+ result = json.dumps({"error": f"Unknown tool: {tool_name}"})
253
+
254
+ return CallToolResult(content=[TextContent(type="text", text=result)])
255
+ except Exception as e:
256
+ return CallToolResult(
257
+ content=[TextContent(type="text", text=json.dumps({"error": str(e)}))]
258
+ )
259
+
260
+ async def list_tools(self, request: ListToolsRequest) -> ListToolsResult:
261
+ """List available tools."""
262
+ return ListToolsResult(tools=self.tools)
263
+
264
+
265
+ # Server initialization
266
+
267
+ async def main():
268
+ """Main entry point for the MCP server."""
269
+ server = MCPServer()
270
+
271
+ # Use stdio transport for MCP
272
+ from mcp.server import Server
273
+
274
+ mcp_server = Server("moltlang")
275
+
276
+ @mcp_server.list_tools()
277
+ async def list_tools_handler() -> list[Tool]:
278
+ return await server.list_tools(ListToolsRequest())
279
+
280
+ @mcp_server.call_tool()
281
+ async def call_tool_handler(name: str, arguments: dict) -> list[TextContent]:
282
+ request = CallToolRequest(
283
+ jsonrpc="2.0",
284
+ id=1,
285
+ params=type("Params", (), {"name": name, "arguments": arguments})(),
286
+ )
287
+ result = await server.call_tool(request)
288
+ return [c for c in result.content if isinstance(c, TextContent)]
289
+
290
+ async with stdio_server() as (read_stream, write_stream):
291
+ await mcp_server.run(
292
+ read_stream,
293
+ write_stream,
294
+ InitializationOptions(
295
+ server_name="moltlang",
296
+ server_version="0.1.0",
297
+ capabilities={"tools": {}},
298
+ ),
299
+ )
300
+
301
+
302
+ if __name__ == "__main__":
303
+ asyncio.run(main())
moltlang/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """
2
+ MoltLang - A Language for LLMs, by LLMs
3
+
4
+ This package provides an AI-optimized language for efficient AI-to-AI communication,
5
+ with bidirectional translation between MoltLang and human languages (starting with English).
6
+
7
+ Example usage:
8
+ >>> from moltlang import translate_to_molt, translate_from_molt
9
+ >>> molt = translate_to_molt("Fetch data from API")
10
+ >>> print(molt)
11
+ [OP:FETCH][SRC:API]
12
+ >>> english = translate_from_molt(molt)
13
+ >>> print(english)
14
+ 'Fetch data from API'
15
+ """
16
+
17
+ __version__ = "0.1.0"
18
+ __author__ = "Jason"
19
+ __license__ = "AGPL-3.0"
20
+
21
+ from moltlang.translator import translate_to_molt, translate_from_molt, MoltTranslator, TranslationResult
22
+ from moltlang.tokens import Token, TokenType, TokenRegistry
23
+ from moltlang.validator import validate_translation, MoltValidator, TranslationQuality
24
+ from moltlang.config import MoltConfig
25
+
26
+ __all__ = [
27
+ "translate_to_molt",
28
+ "translate_from_molt",
29
+ "MoltTranslator",
30
+ "MoltValidator",
31
+ "validate_translation",
32
+ "TranslationQuality",
33
+ "Token",
34
+ "TokenType",
35
+ "TokenRegistry",
36
+ "MoltConfig",
37
+ "TranslationResult",
38
+ "translate_to_molt_result",
39
+ "translate_from_molt_result",
40
+ ]
41
+
42
+
43
+ def translate_to_molt_result(text: str, config: MoltConfig | None = None) -> TranslationResult:
44
+ """
45
+ Translate to MoltLang and return full TranslationResult.
46
+
47
+ This is for MCP/bridge usage where metadata is required.
48
+ """
49
+ from moltlang.translator import MoltTranslator
50
+
51
+ translator = MoltTranslator()
52
+ return translator.translate_to_molt(text, config)
53
+
54
+
55
+ def translate_from_molt_result(molt_text: str, config: MoltConfig | None = None) -> TranslationResult:
56
+ """
57
+ Translate from MoltLang and return full TranslationResult.
58
+
59
+ This is for MCP/bridge usage where metadata is required.
60
+ """
61
+ from moltlang.translator import MoltTranslator
62
+
63
+ translator = MoltTranslator()
64
+ return translator.translate_from_molt(molt_text, config)