Skip to content

Declarative, high-level MCP server API #116

Closed as not planned
Closed as not planned

Description

@wong2

Just like the Python SDK integrates FastMCP modelcontextprotocol/python-sdk#106
I think the TypeScript SDK can also integrate LiteMCP from the TypeScript ecosystem. It was inspired by FastMCP and offers a similar high-level API for developing MCP servers in TypeScript.

Activity

  1. added
    enhancementRequest for a new feature that's not currently supported
    on Jan 6, 2025
  2. jspahrsummers commented on Jan 6, 2025

    @jspahrsummers
    Member

    We're definitely aware of LiteMCP, as well as similar projects easy-mcp and fastmcp.

    I do think the SDK needs improvement, specifically for ease of use, but I'm not convinced that these approaches offer much more than the SDK as authored today. The huge advantage of FastMCP in Python is its declarative nature.

    We probably do want to make the TypeScript SDK more Express-like in usage, but this seems a comparatively minor change. If anyone has ideas for a declarative SDK, though, that'd be interesting!

  3. changed the title [-]Integrating LiteMCP for high-level MCP server API[/-] [+]Declarative, high-level MCP server API[/+] on Jan 6, 2025
  4. zcaceres commented on Jan 22, 2025

    @zcaceres

    @jspahrsummers I recently pushed up a proof of concept of a declarative API in EasyMCP.

    // This decorator creates a root for the MCP
    @Root("/my-root-dir")
    class ZachsMCP extends EasyMCP {
      /**
      You can declare a with zero configuration. Relevant types and plumbing will be inferred and handled.
    
      By default, the *name* of the Tool will be the name of the method.
      */
      @Tool()
      simpleFunc(nickname: string, height: number) {
        return `${nickname} of ${height} height`;
      }
    }

    Here's a video of it.

    It uses Reflect and essentially hacks on the function .prototype to work. There are various rough edges. For example, you can't pass in argument objects when declaring functions.

    But it made me believe that this is possible.

    With some polish, I think there's a version that could work now as an experimental API.

    My conclusion is that the next place to investigate is a custom compile time Typescript transformer. It would likely lead to elegant output with precise types rather than the brittle inference my current decorator supports.

  5. jspahrsummers commented on Jan 22, 2025

    @jspahrsummers
    Member

    Yeah, I was also exploring decorators—but they're unfortunately quite unconventional in JS, and require an OO style to utilize too (can't apply them to free functions).

    A TypeScript transformer seems promising, so long as it's not the only way to access key functionality (not everyone wants to use TS).

  6. zcaceres commented on Jan 22, 2025

    @zcaceres

    Yeah I don't think the language lends itself in the same way as Python.

    IMO the primary savings are in the input declarations. So any pattern that can infer the types and generate those configs would be a net win.

    I also considered whether a React-like declarative API could be an alternative to Decorators -- sure to elicit strong opinions 😁

    <MCPServer>
    <Tool />
    <Resource url={} fn={} />
    </MCPServer>

    As for a transformer, I see it as a way to achieve maximum abstraction but where the default could always be a more verbose Express-like pattern.

  7. jspahrsummers commented on Jan 22, 2025

    @jspahrsummers
    Member

    Actually, JSX isn't a terrible idea! The thought didn't even cross my mind, but I kinda like it. 😂

  8. zcaceres commented on Jan 22, 2025

    @zcaceres

    Actually, JSX isn't a terrible idea! The thought didn't even cross my mind, but I kinda like it. 😂

    I agree! But I'm not the one who's going to have to listen to the anti-JSX complaining in the Issues section 😂

  9. jspahrsummers commented on Jan 23, 2025

    @jspahrsummers
    Member

    Just playing around with the quick start example in imagined JSX:

    function server() {
      const add = async ({ a, b }) => ({
        content: [{ type: "text", text: String(a + b) }]
      });
    
      const loadResource = async (uri, { name }) => ({
        contents: [{
          uri: uri.href,
          text: `Hello, ${name}!`
        }]
      })
    
      return (
        <McpServer name="Demo" version="1.0.0">
          <Tool name="add" input={{ a: z.number(), b: z.number() }} oncall={add} />
          <Resources name="greeting" template="greeting://{name}" onload={loadResource}>
            <Resource uri="greeting://Alice" name="Alice" />
            <Resource uri="greeting://Bob" name="Bob" />
          </Resources>
        </McpServer>
      );
    }

    Or maybe tool arguments could be defined more naturally like this:

    <Tool name="add" oncall={add}>
      <Input name="a" type={z.number()} />
      <Input name="b" type={z.number()} />
    </Tool>

    I dunno if it's better or not. Will noodle on it.

  10. zcaceres commented on Jan 23, 2025

    @zcaceres

    I think it's cool. And to the extent the JSX is sugar around the Express-like API, it could be an interesting other form factor.

    I also like the use of zod to abstract some of the input schema generation.

  11. ondrsh commented on Jan 24, 2025

    @ondrsh

    The cool thing about TS transformers is having access to JSDocs. This means users can write normal code+docs and the transformer generates the complete JSON schemas, including tool and parameter descriptions. I'm doing this with mcp4k (in my case I'm using a lightweight compiler plugin).

    This is not just useful for removing boiler-plate and readability, it also has the benefit of having other tooling (TypeDoc, IDE plugins etc.) work out of the box as they recognize and know JSDocs.

    Looking at the bigger picture, this also helps LLMs write MCP applications. LLMs will be better at just writing "normal TS code" (which they are extremely good at) without having a set of MCP-specific rules to keep in mind.

    I totally get the issue @jspahrsummers mentioned regarding JS compatibility though. Maybe this could be implemented for TS consumers while still allowing JS consumers doing it the "old way"? I'd love to help but my TS skills are limited.

  12. liudonghua123 commented on Mar 24, 2025

    @liudonghua123

    Yeah, I would also like the decorator features of typescript. If the code is written in typescript, use decorator style would make the code clean, tidy and more readable.

    For example, the following demo code in readme

    // Simple tool with parameters
    server.tool(
      "calculate-bmi",
      {
        weightKg: z.number(),
        heightM: z.number()
      },
      async ({ weightKg, heightM }) => ({
        content: [{
          type: "text",
          text: String(weightKg / (heightM * heightM))
        }]
      })
    );
    
    // Async tool with external API call
    server.tool(
      "fetch-weather",
      { city: z.string() },
      async ({ city }) => {
        const response = await fetch(`https://api.weather.com/${city}`);
        const data = await response.text();
        return {
          content: [{ type: "text", text: data }]
        };
      }
    );

    Could rewrite it as the follows.

    // Simple tool with parameters
    @server.tool("calculate-bmi")
    async function({ weightKg: number, heightM: number }) {
      return content: [{
        type: "text",
        text: String(weightKg / (heightM * heightM))
      }];
    }
    
    // Async tool with external API call
    @server.tool("fetch-weather")
    async function ({ city: str }) {
      const response = await fetch(`https://api.weather.com/${city}`);
      const data = await response.text();
      return {
        content: [{ type: "text", text: data }]
      };
    }

    And the decorator style code is more more like python.

    import httpx
    from mcp.server.fastmcp import FastMCP
    
    mcp = FastMCP("My App")
    
    
    @mcp.tool()
    def calculate_bmi(weight_kg: float, height_m: float) -> float:
        """Calculate BMI given weight in kg and height in meters"""
        return weight_kg / (height_m**2)
    
    
    @mcp.tool()
    async def fetch_weather(city: str) -> str:
        """Fetch current weather for a city"""
        async with httpx.AsyncClient() as client:
            response = await client.get(f"https://api.weather.com/{city}")
            return response.text

    See also https://github.com/tc39/proposal-decorators, https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#decorators.

  13. jspahrsummers commented on Mar 24, 2025

    @jspahrsummers
    Member

    @liudonghua123 Your example is not possible with decorators, as they are required to be applied to class methods, not free functions.

  14. liudonghua123 commented on Mar 24, 2025

    @liudonghua123

    @liudonghua123 Your example is not possible with decorators, as they are required to be applied to class methods, not free functions.

    yes, i read the related documentation and noticed this limitation, maybe this can implement in the future's proposal's.

    It can only wrapped in a class or use some other strategies like higher order functions used in react currently.

  15. lloydzhou commented on Apr 1, 2025

    @lloydzhou

    another way to define tool

    by using ts-transformer-zod

    interface BMIParam {
        iweightKg: number;
        heightM: string;
    }
    
    server.tool<BMIParam>(
      "calculate-bmi",
      async (args: BMIParam) => {
        const { weightKg, heightM } = args
        return {
          content: [{
            type: "text",
            text: String(weightKg / (heightM * heightM))
          }]
        }
      }
    );
    
    1. install dependency
    pnpm add -D ts-transformer-zod ts-patch
    
    ts-patch install
    
    1. update tsconfig.json, and replace build command tsc to tspc
    {
      "compilerOptions": {
        "plugins": [
          { "transform": "ts-transformer-zod/transformer" }
        ]
      }
    }
    
    1. Overloading tool functions (this not impalement yet)

    Support generic types

    import { zobject } from "ts-transformer-zod";
    
    tool<T>(
        name: string,
        description: string,
        cb: ToolCallback<T>,
    ): void {
        const paramsSchema = zobject<T>(); // just transformer to zod object
        // ....
    }
    
  16. added a commit that references this issue on May 2, 2025
  17. added
    ready for workEnough information for someone to start working on
    P3Nice to haves, rare edge cases
    on Oct 24, 2025
  18. added this to the v2 milestone on Oct 24, 2025
  19. renatomarinho commented on Mar 19, 2026

    @renatomarinho

    We built exactly this — sharing our learnings

    We ran into this exact frustration building production MCP servers at scale. The SDK gives you the building blocks, but leaves all the hard decisions to you: how to structure tool responses so the LLM doesn't hallucinate, how to prevent tools from being called in invalid states, how to redact PII before it hits the provider, how to handle edge deployments consistently.

    We ended up building Vurb.ts to answer these questions. A few patterns we found valuable that might inform the v2 declarative API design:

    1. MVA (Model-View-Agent) — separating handler from AI perception
    Instead of returning raw data directly, a Presenter layer controls exactly what the LLM sees — field-level schema validation via Zod .strict(), PII redaction, cognitive hints, and next-action affordances. New DB columns added to a query are invisible to the LLM unless explicitly declared in the Presenter schema.

    2. FSM State Gates — structural anti-hallucination
    Tools that shouldn't be callable in a given state don't appear in tools/list at all. It's structurally impossible for the LLM to call cart.pay on an empty cart — not because of runtime validation, but because the tool doesn't exist in that state. Uses XState v5 internally, serverless-ready.

    3. File-based routing
    src/tools/cart/add.ts → automatically becomes the cart.add tool. Zero registration boilerplate — the framework discovers and registers tools from the filesystem.

    These patterns reduced hallucination retries significantly in our production deployments. Happy to discuss any of these if helpful for the v2 declarative API design — or to contribute directly. The repo is open: https://github.com/vinkius-labs/vurb.ts

  20. scottslewis commented on Mar 20, 2026

    @scottslewis

    From the discussion above it appeared that tool decorators might be added to the ts sdk in response to this issue, but it seems not to have happened so far. Plans or comments specifically about tool decorators?

    For everyone's info: a toolgroup class decorator exists now in this python-sdk extension.

    Further, I'm working on a toolgroup impl for the typescript sdk modeled after the python-sdk extension. As part of this effort, I can create tool method decorators myself, but if in the sdk now or in the future, I would prefer to reuse them.

    We built exactly this — sharing our learnings and MVA

    Very cool!

  21. KKonstantinov commented on Mar 26, 2026

    @KKonstantinov
    Contributor

    Hello, thanks for this discussion. Since its original OP post, it seems to have diverged a lot, and the SDK has since moved on quite a bit. thus closing.

    There are no current plans to add tool decorators for v2, as previous discussion highlights it works only for an OO-style in typescript. This could be achieved on-demand by SDK users if needed.

    Please open up specific issues if there are such.

  22. liudonghua123 commented on Mar 26, 2026

    @liudonghua123

    just for reference, I wrote a simple wrapper like python version of fastmcp on https://github.com/liudonghua123/fastmcp-ts.

  23. scottslewis commented on Mar 26, 2026

    @scottslewis

    Hello, thanks for this discussion. Since its original OP post, it seems to have diverged a lot, and the SDK has since moved on quite a bit. thus closing.

    There are no current plans to add tool decorators for v2, as previous discussion highlights it works only for an OO-style in typescript. This could be achieved on-demand by SDK users if needed.

    Please explain and/or point to docs (or source) as to how this could be achieved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Nice to haves, rare edge casesenhancementRequest for a new feature that's not currently supportedready for workEnough information for someone to start working on

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions