TID: MCP Auth Middleware and Single-Tenant Planning

I’m going to start a new series, called today-i-did. and what it is is a collection of the things I did and learned that day. I want to spread any knowledge, and let loose while writing and building that writing muscle.

An eventful day it was today, having to implement some new features for an MCP server, while also balancing side-hustle work and CTO burdens. It all started with some Nest.js, good ole safe nest.js, that looks and smells like a Springy Boot.

I learned about middleware in Nest.js and Exception filters. Middleware works the same as middleware does in Express.js, but the exception filter was a fun new thing for me. Working the same way it does in Spring, an exception filter will catch an exception thrown anywhere in the web application stack and handle it.

https://docs.nestjs.com/exception-filters#exception-filters-1

The documentation describes it pretty well

While the base (built-in) exception filter can automatically handle many cases for you, you may want full control over the exceptions layer. For example, you may want to add logging or use a different JSON schema based on some dynamic factors. Exception filters are designed for exactly this purpose. They let you control the exact flow of control and the content of the response sent back to the client.

In my little corner of the world, I am using it to handle MCP server authentication. So, we are bound by the MCP spec to do the right thing. The spec mentions two things in particular:

  1. A server MUST respond with 401
  2. A server MUST include WWW-Authenticate with details about where to find the resource_metadata_uri for Oauth.

Here’s how that code ended up looking:

@Catch(AuthException)
export class McpAuthFilter implements ExceptionFilter {

    constructor(private readonly mcpService: McpService) {} // (1)
    
    catch(exception: AuthException, host: ArgumentsHost) { // (2)
   
        const ctx = host.switchToHttp()
        const request = ctx.getRequest<Request>()
        const response = ctx.getResponse<Response>()
        
        this.mcpService.deleteTransport(request); // (3)
        
        response.setHeader("WWW-Authenticate", `Bearer resource_metadata_uri="${metadataUri}"`)
            .status(401)
            .send(); // (4)
            
    }
}

Let’s explain this code point by point here.

  1. We are adding as a dependency the McpService that I have written. This service handles the connection management for MCP and thus is needed when trying to delete connections that are no longer authenticated. I don’t think filters have access to the full dependency injection of Nest so have to pass this in manually at app startup.
  2. We implement the one method of the ExceptionFilter interface, to make this into a proper exception filter
  3. We delete the connection that is no longer authenticated, in our case it is keyed to the MCP session ID.
  4. Send the proper, spec-following response to the user.

Register this via something like app.useGlobalFilters(McpAuthFilter) and you are good to go.

Planning Single-Tenant

On the other hand, I have a bunch of work to do still for my CTO project. I have to migrate my application from multi-tenancy to single-tenancy. How I do that though is straightforward, as I designed the app ina simple way. Everything is tied together through the central organizational ID. I need to remove this ID, because that information will become implied. It will all be configuration-driven and stamped out at deploy time for the application containers. It’s likely that I will move to something like a Kubernetes for this setup as it is going to simplify the overhead of managing single-tenant instances quite a bit.

Even further complicating, is thta these per-tenant instances are short-lived. THey are project based. So projects will come and go but I will have to spin up new instances for each one that happens. How to do this as cheaply as possible is an interesting calculation to make. One that I’ve not really had to make before until I became a CTO. That’s now on my radar too.

In planning the single-tenant application though, the only possible shared information between these per-project instances is the users. So, the architecture has to allow for this. There needs to be a single source of truth for user information that any of the projects can pull from, and they can access too as they deal with user data. User imports should be synced from this service, and any user creation should also happen from this service as well. This makes onboarding a lot more interesting.

So, quite a few things on the plate.

Going to try tomorrow to keep working towards that MCP server, but also checking in on another project that I’m working on.

 Share!

 
I run WindleWare! Feel free to reach out!

Subscribe for Exclusive Updates

* indicates required