fontlab-remopy 2.0.9__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.
@@ -0,0 +1,21 @@
1
+ # this_file: src/fontlab_remopy/__init__.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Reusable FontLab remote control; imports remain light inside the host."""
4
+ from importlib import import_module
5
+ from typing import Any
6
+
7
+ _EXPORTS = {"launch":"platforms", "submit_script":"platforms", "ScriptSubmission":"platforms",
8
+ "find_bridge":"platforms", "enable_mcp":"host", "setup_mcp":"setup",
9
+ "bridge_parameters":"mcp", "probe_tools":"mcp", "call_tool":"mcp",
10
+ "run_python":"mcp", "execute_script":"mcp", "NativeExecutionError":"mcp",
11
+ "FontLab":"client", "AsyncFontLab":"client", "ExecutionResult":"results",
12
+ "ResultTransportError":"results"}
13
+ __all__ = list(_EXPORTS)
14
+
15
+
16
+ def __getattr__(name: str) -> Any:
17
+ if name not in _EXPORTS:
18
+ raise AttributeError(name)
19
+ value = getattr(import_module('.'+_EXPORTS[name],__name__),name)
20
+ globals()[name] = value
21
+ return value
@@ -0,0 +1,5 @@
1
+ # this_file: src/fontlab_remopy/__main__.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,101 @@
1
+ # this_file: src/fontlab_remopy/actions.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Named native tool calls shared by synchronous and asynchronous clients."""
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+
9
+ class Controls:
10
+ """Named catalogue calls; async clients return awaitable values.
11
+
12
+ Each method calls one native MCP tool by name and returns its JSON payload;
13
+ keyword arguments are the tool's own parameters (see ``tools()`` for schemas).
14
+ Methods that change FontLab state perform the operation immediately.
15
+ """
16
+
17
+ def list_fonts(self) -> Any:
18
+ """Call ``list_fonts``: every open font, as ``{"fonts": [...]}``."""
19
+ return self.tool("list_fonts")
20
+
21
+ def current_font(self) -> Any:
22
+ """Call ``get_active_font``: the font in the active window."""
23
+ return self.tool("get_active_font")
24
+
25
+ def current_glyphs(self) -> Any:
26
+ """Call ``get_current_glyphs``: the glyphs of the active window."""
27
+ return self.tool("get_current_glyphs")
28
+
29
+ def font_info(self, **arguments: Any) -> Any:
30
+ """Call ``get_font_info`` with the tool's arguments."""
31
+ return self.tool("get_font_info", **arguments)
32
+
33
+ def glyph_info(self, **arguments: Any) -> Any:
34
+ """Call ``get_glyph`` with the tool's arguments."""
35
+ return self.tool("get_glyph", **arguments)
36
+
37
+ def glyph(self, name: str, **arguments: Any) -> Any:
38
+ """Call ``get_glyph`` for the glyph called ``name``."""
39
+ return self.glyph_info(glyph_name=name, **arguments)
40
+
41
+ def list_glyphs(self, **arguments: Any) -> Any:
42
+ """Call ``list_glyphs`` with the tool's arguments."""
43
+ return self.tool("list_glyphs", **arguments)
44
+
45
+ def font_metrics(self, **arguments: Any) -> Any:
46
+ """Call ``get_font_metrics`` with the tool's arguments."""
47
+ return self.tool("get_font_metrics", **arguments)
48
+
49
+ def glyph_metrics(self, **arguments: Any) -> Any:
50
+ """Call ``get_glyph_metrics`` with the tool's arguments."""
51
+ return self.tool("get_glyph_metrics", **arguments)
52
+
53
+ def list_actions(self) -> Any:
54
+ """Call ``list_actions``: the application actions that ``run_actions`` accepts."""
55
+ return self.tool("list_actions")
56
+
57
+ def run_actions(self, **arguments: Any) -> Any:
58
+ """Call ``run_actions``: run application actions. Changes FontLab state."""
59
+ return self.tool("run_actions", **arguments)
60
+
61
+ def output(self, **arguments: Any) -> Any:
62
+ """Call ``get_python_output``: recent Python output captured by the MCP tool."""
63
+ return self.tool("get_python_output", **arguments)
64
+
65
+ def open_font(self, **arguments: Any) -> Any:
66
+ """Call ``open_font``. Opens a font in FontLab."""
67
+ return self.tool("open_font", **arguments)
68
+
69
+ def new_font(self, **arguments: Any) -> Any:
70
+ """Call ``new_font``. Creates an empty font in FontLab."""
71
+ return self.tool("new_font", **arguments)
72
+
73
+ def save_font(self, **arguments: Any) -> Any:
74
+ """Call ``save_font``. Writes the font to disk."""
75
+ return self.tool("save_font", **arguments)
76
+
77
+ def close_font(self, **arguments: Any) -> Any:
78
+ """Call ``close_font``. Closes a font in FontLab."""
79
+ return self.tool("close_font", **arguments)
80
+
81
+ def activate_font(self, **arguments: Any) -> Any:
82
+ """Call ``set_active_font``. Changes which font is active."""
83
+ return self.tool("set_active_font", **arguments)
84
+
85
+ def activate_glyph(self, **arguments: Any) -> Any:
86
+ """Call ``set_active_glyph``. Changes which glyph is active."""
87
+ return self.tool("set_active_glyph", **arguments)
88
+
89
+ def set_font_metrics(self, **arguments: Any) -> Any:
90
+ """Call ``set_font_metrics``. Changes font metrics."""
91
+ return self.tool("set_font_metrics", **arguments)
92
+
93
+ def set_glyph_metrics(self, **arguments: Any) -> Any:
94
+ """Call ``set_glyph_metrics``. Changes glyph metrics."""
95
+ return self.tool("set_glyph_metrics", **arguments)
96
+
97
+ def python(self, function: Callable) -> Callable:
98
+ """Decorate a normal function to execute remotely with JSON values."""
99
+ from .remote import remote_function
100
+
101
+ return remote_function(self, function)
fontlab_remopy/cli.py ADDED
@@ -0,0 +1,100 @@
1
+ # this_file: src/fontlab_remopy/cli.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Explicit launch, verified script execution and native MCP operations."""
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ def main(argv: list[str] | None = None) -> int:
13
+ parser = argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument('--timeout',type=float,default=30)
15
+ parser.add_argument('--bridge',help='Explicit native bridge executable')
16
+ sub = parser.add_subparsers(dest='operation',required=True)
17
+ for operation in ('launch', 'submit'):
18
+ command = sub.add_parser(operation)
19
+ if operation == 'submit':
20
+ command.add_argument('path', type=Path)
21
+ command.add_argument('--backend', choices=('macos', 'crossover', 'wine'), default='macos')
22
+ command.add_argument('--executable', type=Path)
23
+ command.add_argument('--wine', type=Path, help='Explicit Wine/CrossOver launcher')
24
+ selector = command.add_mutually_exclusive_group()
25
+ selector.add_argument('--bottle', help='CrossOver bottle in the standard macOS location')
26
+ selector.add_argument('--prefix', type=Path, help='Existing ordinary Wine prefix')
27
+ sub.add_parser('setup')
28
+ sub.add_parser('tools')
29
+ execute = sub.add_parser('execute')
30
+ execute.add_argument('path',type=Path)
31
+ call = sub.add_parser('call')
32
+ call.add_argument('name')
33
+ call.add_argument('--arguments',type=json.loads,default={})
34
+ args = parser.parse_args(argv)
35
+ try:
36
+ result = asyncio.run(_perform(args))
37
+ except Exception as error: # noqa: BLE001 - CLI boundary reports any SDK or remote failure with exit status 1
38
+ detail = f'{type(error).__name__}: {error}\n'
39
+ if _timed_out(error) and args.operation in {'setup', 'execute', 'call', 'launch', 'submit'}:
40
+ detail += 'Execution outcome is unknown; verify before repeating.\n'
41
+ for note in getattr(error, '__notes__', []):
42
+ detail += note + '\n'
43
+ parser.exit(1,detail)
44
+ print(json.dumps(result,indent=2))
45
+ return 0
46
+
47
+
48
+ def _timed_out(error: BaseException) -> bool:
49
+ if isinstance(error, BaseExceptionGroup):
50
+ return any(_timed_out(child) for child in error.exceptions)
51
+ return isinstance(error, (TimeoutError, subprocess.TimeoutExpired))
52
+
53
+
54
+ async def _perform(args: argparse.Namespace) -> Any:
55
+ from .mcp import call_tool, execute_script, probe_tools
56
+ from .mcp.compat import wire
57
+ from .setup import setup_mcp
58
+ match args.operation:
59
+ case 'launch' | 'submit':
60
+ return _submit(args)
61
+ case 'setup':
62
+ result = await setup_mcp(command=args.bridge,timeout=args.timeout)
63
+ return {'execution_verified':result.execution_verified,'tools':len(result.tools)}
64
+ case 'tools':
65
+ return [wire(tool) for tool in await probe_tools(args.bridge,args.timeout)]
66
+ case 'execute':
67
+ return await execute_script(args.path,args.bridge,args.timeout)
68
+ case 'call':
69
+ return wire(await call_tool(args.name,args.arguments,args.bridge,args.timeout))
70
+ raise ValueError('Unknown operation')
71
+
72
+
73
+ def _submit(args: argparse.Namespace) -> dict[str, Any]:
74
+ from . import platforms
75
+ from .platforms import crossover, wine
76
+
77
+ options: dict[str, Any] = {'timeout': args.timeout}
78
+ provider = platforms
79
+ if args.backend == 'macos':
80
+ if any(value is not None for value in (args.executable, args.wine, args.bottle, args.prefix)):
81
+ raise ValueError('Wine options require an explicit crossover or wine backend')
82
+ else:
83
+ if args.executable is None or args.wine is None:
84
+ raise ValueError('Wine backends require --executable and --wine')
85
+ options.update(executable=args.executable, wine=args.wine)
86
+ if args.backend == 'crossover':
87
+ if not args.bottle or args.prefix is not None:
88
+ raise ValueError('CrossOver requires --bottle and does not accept --prefix')
89
+ provider = crossover
90
+ options['bottle'] = args.bottle
91
+ else:
92
+ if args.prefix is None or args.bottle is not None:
93
+ raise ValueError('Wine requires --prefix and does not accept --bottle')
94
+ provider = wine
95
+ options['prefix'] = args.prefix
96
+ if args.operation == 'launch':
97
+ provider.launch(**options)
98
+ return {'launch_requested': True}
99
+ result = provider.submit_script(args.path, **options)
100
+ return {'path': str(result.path), 'execution_verified': result.execution_verified}
@@ -0,0 +1,225 @@
1
+ # this_file: src/fontlab_remopy/client.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Reusable synchronous and asynchronous FontLab MCP connections."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import json
9
+ import math
10
+ from contextlib import ExitStack, asynccontextmanager
11
+ from functools import partial
12
+ from pathlib import Path
13
+ from typing import Any, Self
14
+
15
+ from anyio.from_thread import start_blocking_portal
16
+ from mcp import ClientSession
17
+ from mcp.client.stdio import stdio_client
18
+ from mcp.types import PaginatedRequestParams
19
+
20
+ from .actions import Controls
21
+ from .mcp import NativeExecutionError, bridge_parameters
22
+ from .mcp.compat import is_error, next_cursor, refuse_unknown, tool_schema, wire
23
+ from .platforms import find_bridge
24
+ from .results import ExecutionResult, decode_execution, encode_execution
25
+
26
+
27
+ @asynccontextmanager
28
+ async def _connection(command: str | None, timeout: float):
29
+ bridge = find_bridge(command)
30
+ if bridge is None:
31
+ raise FileNotFoundError("No executable FontLab MCP bridge found")
32
+ async with (
33
+ stdio_client(bridge_parameters(bridge)) as (read, write),
34
+ ClientSession(read, write) as session,
35
+ ):
36
+ async with asyncio.timeout(timeout):
37
+ await session.initialize()
38
+ yield session
39
+
40
+
41
+ class AsyncFontLab(Controls):
42
+ """One authenticated session; use ``async with`` and await each operation.
43
+
44
+ Enter/exit on the same task, as required by the SDK's structured transport.
45
+ Idle lifetime is unlimited. Calls use the configured timeout without retry.
46
+ """
47
+
48
+ def __init__(self, command: str | None = None, timeout: float = 30) -> None:
49
+ if not math.isfinite(timeout) or timeout <= 0:
50
+ raise ValueError("MCP timeout must be positive")
51
+ self.command, self.timeout = command, timeout
52
+ self._session = None
53
+ self._context = None
54
+ self._lock = asyncio.Lock()
55
+ self._uncertain = False
56
+ self._schemas: dict[str, Any] | None = None # tool name -> inputSchema
57
+
58
+ async def __aenter__(self) -> Self:
59
+ if self._session is not None:
60
+ raise RuntimeError("FontLab is already connected")
61
+ self._context = _connection(self.command, self.timeout)
62
+ self._lock = asyncio.Lock()
63
+ self._session = await self._context.__aenter__()
64
+ self._uncertain = False
65
+ self._schemas = None
66
+ return self
67
+
68
+ async def __aexit__(self, *exc: object) -> None:
69
+ try:
70
+ # User/native script errors belong to the public caller, not the
71
+ # transport task groups. Close normally so SDK teardown does not
72
+ # repackage those errors into nested ExceptionGroups.
73
+ await self._context.__aexit__(None, None, None)
74
+ finally:
75
+ self._session = self._context = None
76
+
77
+ async def _call(self, operation, *args, **kwargs):
78
+ async with self._lock:
79
+ if self._session is None or self._uncertain:
80
+ raise RuntimeError(
81
+ "Connect FontLab with a fresh context before calling"
82
+ )
83
+ try:
84
+ async with asyncio.timeout(self.timeout):
85
+ return await getattr(self._session, operation)(*args, **kwargs)
86
+ except (TimeoutError, asyncio.CancelledError) as error:
87
+ self._uncertain = True
88
+ error.add_note(
89
+ "FontLab execution outcome may be unknown; never retry automatically"
90
+ )
91
+ raise
92
+
93
+ async def tools(self) -> list[Any]:
94
+ """Discover the complete native tool catalogue (every page)."""
95
+ result, cursor = [], None
96
+ while True:
97
+ page = await self._call(
98
+ "list_tools", params=PaginatedRequestParams(cursor=cursor)
99
+ )
100
+ result.extend(page.tools)
101
+ cursor = next_cursor(page)
102
+ if not cursor:
103
+ return result
104
+
105
+ async def _check_arguments(self, name: str, arguments: dict[str, Any]) -> None:
106
+ """Refuse argument names the tool's schema does not declare.
107
+
108
+ FontLab silently drops unknown names, so a misspelt ``master`` on a write
109
+ tool acts on the current master. Names only; values are not validated.
110
+ """
111
+ if self._schemas is None:
112
+ self._schemas = {t.name: tool_schema(t) for t in await self.tools()}
113
+ refuse_unknown(name, self._schemas.get(name), arguments)
114
+
115
+ async def tool(self, name: str, **arguments: Any) -> Any:
116
+ """Return the catalogue's JSON payload; preserve native/tool failures.
117
+
118
+ Argument names are checked against the live catalogue (fetched once per
119
+ connection); an unknown name raises ``ValueError`` before anything is sent.
120
+ """
121
+ json.dumps(arguments, allow_nan=False)
122
+ await self._check_arguments(name, arguments)
123
+ return await self._tool(name, arguments)
124
+
125
+ async def _tool(self, name: str, arguments: dict[str, Any]) -> Any:
126
+ result = await self._call("call_tool", name, arguments=arguments)
127
+ if is_error(result):
128
+ raise NativeExecutionError(wire(result))
129
+ texts = [item.text for item in result.content if item.type == "text"]
130
+ if len(texts) != 1:
131
+ raise RuntimeError("FontLab tool returned no single JSON payload")
132
+ return json.loads(texts[0])
133
+
134
+ async def run(self, code: str, /, **variables: Any) -> ExecutionResult:
135
+ """Execute ordinary Python with JSON variables and captured output."""
136
+ return await self._execute(code, variables, "<fontlab-remopy>")
137
+
138
+ async def fonts(self) -> list[dict[str, Any]]:
139
+ """Return open-font records without the catalogue's outer object."""
140
+ return (await self.list_fonts())["fonts"]
141
+
142
+ async def _execute(self, code, variables, filename):
143
+ wrapped, nonce = encode_execution(code, variables, filename)
144
+ payload = await self._tool("run_python", {"code": wrapped})
145
+ return decode_execution(payload, nonce)
146
+
147
+ async def eval(self, expression: str, /, **variables: Any) -> Any:
148
+ """Evaluate an expression and return its JSON-native Python value."""
149
+ return (await self.run("result = (" + expression + "\n)", **variables)).value
150
+
151
+ async def execute_script(
152
+ self, path: str | Path, /, **variables: Any
153
+ ) -> ExecutionResult:
154
+ """Run a .flpy/.vfpy file like ``run``; ``__file__`` is its resolved path."""
155
+ path = Path(path).expanduser().resolve()
156
+ return await self._execute(
157
+ path.read_text(encoding="utf-8-sig"), variables, str(path)
158
+ )
159
+
160
+
161
+ class FontLab(Controls):
162
+ """Simple Python control, including notebooks with a running event loop.
163
+
164
+ ``with FontLab() as fl: answer = fl.eval('value + 2', value=40)``
165
+ Owns its portal thread and bridge until close/context exit.
166
+ """
167
+
168
+ def __init__(self, command: str | None = None, timeout: float = 30) -> None:
169
+ self._async = AsyncFontLab(command, timeout)
170
+ self._stack = None
171
+ self._portal = None
172
+
173
+ def __enter__(self) -> Self:
174
+ if self._stack is not None:
175
+ raise RuntimeError("FontLab is already connected")
176
+ stack = ExitStack()
177
+ try:
178
+ self._portal = stack.enter_context(start_blocking_portal())
179
+ stack.enter_context(self._portal.wrap_async_context_manager(self._async))
180
+ except BaseException:
181
+ stack.close()
182
+ self._portal = None
183
+ raise
184
+ self._stack = stack
185
+ return self
186
+
187
+ def __exit__(self, *exc: object) -> bool | None:
188
+ try:
189
+ return self._stack.__exit__(*exc)
190
+ finally:
191
+ self._stack = self._portal = None
192
+
193
+ def close(self) -> None:
194
+ """Idempotently release the authenticated bridge and portal thread."""
195
+ if self._stack is not None:
196
+ self.__exit__(None, None, None)
197
+
198
+ def _call(self, method, *args, **kwargs):
199
+ if self._portal is None:
200
+ raise RuntimeError("Connect FontLab using a with context before calling")
201
+ return self._portal.call(partial(getattr(self._async, method), *args, **kwargs))
202
+
203
+ def tools(self) -> list[Any]:
204
+ """Discover the complete authenticated native tool catalogue."""
205
+ return self._call("tools")
206
+
207
+ def fonts(self) -> list[dict[str, Any]]:
208
+ """Return open-font records without the catalogue's outer object."""
209
+ return self._call("fonts")
210
+
211
+ def tool(self, name: str, **arguments: Any) -> Any:
212
+ """Call any native catalogue tool by name; return its JSON payload."""
213
+ return self._call("tool", name, **arguments)
214
+
215
+ def run(self, code: str, /, **variables: Any) -> ExecutionResult:
216
+ """Execute ordinary Python with JSON variables and captured output."""
217
+ return self._call("run", code, **variables)
218
+
219
+ def eval(self, expression: str, /, **variables: Any) -> Any:
220
+ """Evaluate an expression and return its JSON-native Python value."""
221
+ return self._call("eval", expression, **variables)
222
+
223
+ def execute_script(self, path: str | Path, /, **variables: Any) -> ExecutionResult:
224
+ """Run a .flpy/.vfpy file like ``run``; ``__file__`` is its resolved path."""
225
+ return self._call("execute_script", path, **variables)
@@ -0,0 +1,26 @@
1
+ # this_file: src/fontlab_remopy/discovery.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Portable bridge discovery and application submission data."""
4
+
5
+ import os
6
+ import shutil
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ DEFAULT_APP = Path("/Applications/FontLab 9.app")
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ScriptSubmission:
15
+ path: Path
16
+ execution_verified: bool = False
17
+
18
+
19
+ def find_bridge(command: str | Path | None = None) -> str | None:
20
+ """Find an executable without splitting paths containing spaces."""
21
+ override = command or os.environ.get('FONTLAB_MCP_COMMAND') or os.environ.get('AIDUS_FONTLAB_MCP_COMMAND')
22
+ if override:
23
+ return shutil.which(str(Path(override).expanduser()))
24
+ candidates = [shutil.which('fontlab-mcp'), str(DEFAULT_APP/'Contents/MacOS/fontlab-mcp'),
25
+ str(Path.home()/'Applications/FontLab 9.app/Contents/MacOS/fontlab-mcp')]
26
+ return next((path for path in candidates if path and os.access(path,os.X_OK)),None)
fontlab_remopy/host.py ADDED
@@ -0,0 +1,15 @@
1
+ # this_file: src/fontlab_remopy/host.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """MCP preference setup using the host's verified extended-preference API."""
4
+
5
+
6
+ def enable_mcp(enabled: bool = True) -> None:
7
+ """Run inside FontLab; update only mcp.enabled and notify the host."""
8
+ try:
9
+ import fontlab
10
+ except ModuleNotFoundError as error:
11
+ if error.name == 'fontlab':
12
+ raise RuntimeError('enable_mcp requires execution inside FontLab') from error
13
+ raise
14
+ fontlab.flPreferences().load({'mcp.enabled':enabled})
15
+ fontlab.flItems.notifyPreferencesChanged()
@@ -0,0 +1,125 @@
1
+ # this_file: src/fontlab_remopy/mcp/__init__.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Authenticated native MCP calls through the MCP SDK (v1 or v2) and relay."""
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import json
8
+ import os
9
+ import sys
10
+ from collections.abc import AsyncIterator
11
+ from contextlib import asynccontextmanager
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from mcp import ClientSession, StdioServerParameters
16
+ from mcp.client.stdio import stdio_client
17
+ from mcp.types import CallToolResult, PaginatedRequestParams, Tool
18
+
19
+ from ..platforms import find_bridge
20
+ from .compat import is_error, next_cursor, refuse_unknown, tool_schema, wire
21
+
22
+
23
+ class NativeExecutionError(RuntimeError):
24
+ """Native execution completed with a tool or embedded Python error."""
25
+ def __init__(self, payload: dict[str, Any]) -> None:
26
+ self.payload = payload
27
+ super().__init__('FontLab execution failed: '+str(payload.get('error',payload)))
28
+
29
+
30
+ def relay_python() -> str:
31
+ """Return the Python that runs the relay; refuse FontLab's own executable.
32
+
33
+ Inside FontLab, sys.executable is the application. Launching it with
34
+ Python arguments starts a second FontLab that holds the pipes open.
35
+ """
36
+ if not sys.executable:
37
+ raise RuntimeError('fontlab_remopy has no Python executable to run the relay with.')
38
+ if Path(sys.executable).name.lower().startswith('fontlab'):
39
+ raise RuntimeError(
40
+ 'fontlab_remopy is an external client: sys.executable is FontLab itself '
41
+ f'({sys.executable}). Run it from a separate Python, not inside FontLab.')
42
+ return sys.executable
43
+
44
+
45
+ def bridge_parameters(command: str) -> StdioServerParameters:
46
+ """Use one SDK relay for all callers, including external coding agents."""
47
+ return StdioServerParameters(command=relay_python(),
48
+ args=['-m','fontlab_remopy.mcp.relay',command],env=os.environ.copy())
49
+
50
+
51
+ @asynccontextmanager
52
+ async def _session(command: str | None, timeout: float) -> AsyncIterator[ClientSession]:
53
+ if timeout <= 0:
54
+ raise ValueError('MCP timeout must be positive')
55
+ bridge = find_bridge(command)
56
+ if bridge is None:
57
+ raise FileNotFoundError('No executable FontLab MCP bridge found')
58
+ async with (
59
+ asyncio.timeout(timeout),
60
+ stdio_client(bridge_parameters(bridge)) as (read,write),
61
+ ClientSession(read,write) as session,
62
+ ):
63
+ await session.initialize()
64
+ yield session
65
+
66
+
67
+ async def _list_all(session: ClientSession) -> list[Tool]:
68
+ tools: list[Tool] = []
69
+ cursor = None
70
+ while True:
71
+ page = await session.list_tools(params=PaginatedRequestParams(cursor=cursor))
72
+ tools.extend(page.tools)
73
+ cursor = next_cursor(page)
74
+ if not cursor:
75
+ return tools
76
+
77
+
78
+ async def probe_tools(command: str | None = None, timeout: float = 8) -> list[Tool]:
79
+ """Discover every page; initialization alone does not prove host reachability."""
80
+ async with _session(command,timeout) as session:
81
+ return await _list_all(session)
82
+
83
+
84
+ async def call_tool(name: str, arguments: dict[str, Any] | None = None,
85
+ command: str | None = None, timeout: float = 30,
86
+ *, check_arguments: bool = True) -> CallToolResult:
87
+ """Return the actual SDK result; never retry a mutation after timeout.
88
+
89
+ Unknown argument names raise ``ValueError`` before anything is sent, because
90
+ FontLab silently drops them. This costs one catalogue request per call.
91
+ """
92
+ if arguments is not None and not isinstance(arguments, dict):
93
+ raise TypeError('MCP tool arguments must be a dictionary')
94
+ async with _session(command,timeout) as session:
95
+ if check_arguments and arguments:
96
+ schemas = {t.name: tool_schema(t) for t in await _list_all(session)}
97
+ refuse_unknown(name, schemas.get(name), arguments)
98
+ result = await session.call_tool(name,arguments=arguments or {})
99
+ return result
100
+
101
+
102
+ async def run_python(code: str, command: str | None = None, timeout: float = 30) -> dict[str, Any]:
103
+ """Require both transport success and a native execution success payload."""
104
+ result = await call_tool('run_python',{'code':code},command,timeout,check_arguments=False)
105
+ if is_error(result):
106
+ raise NativeExecutionError(wire(result))
107
+ for item in result.content:
108
+ if item.type != 'text':
109
+ continue
110
+ payload = json.loads(item.text)
111
+ if not isinstance(payload,dict) or not isinstance(payload.get('success'),bool):
112
+ raise RuntimeError('Unexpected FontLab run_python payload') # noqa: TRY004 - preserve the public malformed-response exception
113
+ if not payload['success']:
114
+ raise NativeExecutionError(payload)
115
+ return payload
116
+ raise RuntimeError('FontLab run_python returned no execution payload')
117
+
118
+
119
+ async def execute_script(path: str | Path, command: str | None = None, timeout: float = 30) -> dict[str, Any]:
120
+ """Execute .flpy/.vfpy text via native MCP and preserve script filename context."""
121
+ path = Path(path).expanduser().resolve()
122
+ source = path.read_text(encoding='utf-8-sig')
123
+ namespace = {'__name__':'__main__','__file__':str(path)}
124
+ code = f'exec(compile({source!r}, {str(path)!r}, "exec"), {namespace!r})'
125
+ return await run_python(code,command,timeout)