|
| 1 | +import re |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from mcp import SamplingMessage |
| 5 | +from mcp.server.fastmcp import Context, FastMCP |
| 6 | +from mcp.server.session import ServerSessionT |
| 7 | +from mcp.shared.context import LifespanContextT, RequestT |
| 8 | +from mcp.types import TextContent |
| 9 | + |
| 10 | +app = FastMCP(log_level='WARNING') |
| 11 | + |
| 12 | +import logfire |
| 13 | + |
| 14 | +logfire.configure(service_name='mcp-sampling-server', console=False) |
| 15 | +logfire.instrument_mcp() |
| 16 | + |
| 17 | + |
| 18 | +@app.tool() |
| 19 | +async def image_generator(ctx: Context[ServerSessionT, LifespanContextT, RequestT], subject: str, style: str) -> str: |
| 20 | + prompt = f'{subject=} {style=}' |
| 21 | + # `ctx.session.create_message` is the sampling call |
| 22 | + result = await ctx.session.create_message( |
| 23 | + [SamplingMessage(role='user', content=TextContent(type='text', text=prompt))], |
| 24 | + max_tokens=1_024, |
| 25 | + system_prompt='Generate an SVG image as per the user input', |
| 26 | + ) |
| 27 | + assert isinstance(result.content, TextContent) |
| 28 | + |
| 29 | + path = Path(f'{subject}_{style}.svg') |
| 30 | + # remove triple backticks if the svg was returned within markdown |
| 31 | + if m := re.search(r'^```\w*$(.+?)```$', result.content.text, re.S | re.M): |
| 32 | + path.write_text(m.group(1)) |
| 33 | + else: |
| 34 | + path.write_text(result.content.text) |
| 35 | + return f'See {path}' |
| 36 | + |
| 37 | + |
| 38 | +if __name__ == '__main__': |
| 39 | + # run the server via stdio |
| 40 | + app.run() |
0 commit comments