Skip to content

A platform for community discussion. Free, open, simple.

15.0 KB
Raw Blame
# frozen_string_literal: true

describe "MCP transport" do
  fab!(:admin)

  let(:client) do
    McpOauthClient.create!(
      client_id: "request-spec-client",
      name: "Request spec client",
      registration_type: "pre_registered",
      trust_state: "approved",
      redirect_uris: ["http://127.0.0.1/callback"],
    )
  end
  let(:authorization) do
    DiscourseMcp::OAuth::AuthorizationGrant.create!(
      user: admin,
      client: client,
      redirect_uri: client.redirect_uris.first,
      requested_scopes: %w[mcp:profile:read],
    )
  end
  let(:access_token) { McpOauthAccessToken.issue!(authorization: authorization) }
  let(:headers) do
    {
      "HTTP_AUTHORIZATION" => "Bearer #{access_token}",
      "CONTENT_TYPE" => "application/json",
      "HTTP_ACCEPT" => "application/json, text/event-stream",
      "HTTP_MCP_PROTOCOL_VERSION" => DiscourseMcp::PROTOCOL_VERSION,
      "HTTP_MCP_METHOD" => "tools/call",
      "HTTP_MCP_NAME" => "discourse_current_user_get",
    }
  end
  let(:classic_headers) do
    headers.slice("HTTP_AUTHORIZATION", "CONTENT_TYPE", "HTTP_ACCEPT").merge(
      "HTTP_MCP_PROTOCOL_VERSION" => "2025-11-25",
    )
  end
  let(:initialize_payload) do
    {
      jsonrpc: "2.0",
      id: 0,
      method: "initialize",
      params: {
        protocolVersion: "2025-11-25",
        capabilities: {
          roots: {
            listChanged: true,
          },
        },
        clientInfo: {
          name: "compatible-client",
          version: "1.0.0",
        },
      },
    }
  end
  let(:payload) do
    {
      jsonrpc: "2.0",
      id: 1,
      method: "tools/call",
      params: {
        name: "discourse_current_user_get",
        arguments: {
        },
        _meta: {
          "io.modelcontextprotocol/protocolVersion" => DiscourseMcp::PROTOCOL_VERSION,
          "io.modelcontextprotocol/clientCapabilities" => {
          },
        },
      },
    }
  end

  before do
    SiteSetting.mcp_server_enabled = true
    McpPrimitive.create!(kind: "tool", identifier: "discourse_current_user_get", enabled: true)
  end

  it "filters hidden private-message content before paginating for MCP participants" do
    participant = Fabricate(:user)
    author = Fabricate(:user)
    message = Fabricate(:private_message_post, user: author, recipient: participant)
    hidden_post =
      Fabricate(
        :post,
        topic: message.topic,
        user: author,
        hidden: true,
        raw: "Restricted PM content",
      )
    visible_post = Fabricate(:post, topic: message.topic, user: author)
    trailing_hidden_post =
      Fabricate(
        :post,
        topic: message.topic,
        user: author,
        hidden: true,
        raw: "Further restricted content",
      )
    tool_name = "discourse_read_private_message"
    McpPrimitive.create!(kind: "tool", identifier: tool_name, enabled: true)
    group = Fabricate(:group)
    group.add(participant)
    group.add(author)
    McpGroupScope.create!(group: group, scope: "mcp:private-messages:read")

    [participant, author, admin].each do |viewer|
      grant =
        DiscourseMcp::OAuth::AuthorizationGrant.create!(
          user: viewer,
          client: client,
          redirect_uri: client.redirect_uris.first,
          requested_scopes: %w[mcp:profile:read mcp:private-messages:read],
        )
      token = McpOauthAccessToken.issue!(authorization: grant)
      read_payload =
        payload.deep_merge(
          params: {
            name: tool_name,
            arguments: {
              topic_id: message.topic_id,
              start_post_number: hidden_post.post_number,
              post_limit: 1,
            },
          },
        )

      post "/mcp",
           params: read_payload.to_json,
           headers:
             headers.merge("HTTP_AUTHORIZATION" => "Bearer #{token}", "HTTP_MCP_NAME" => tool_name)

      expect(response.status).to eq(200)
      result = response.parsed_body.fetch("result").fetch("structuredContent")
      expected_post = viewer == participant ? visible_post : hidden_post
      if viewer == participant
        expect(response.body).not_to include(hidden_post.raw, trailing_hidden_post.raw)
      end
      expect(result.fetch("posts").pluck("id")).to eq([expected_post.id])
      expect(result.fetch("posts").sole.fetch("raw")).to eq(expected_post.raw)
      expect(result.fetch("meta")).to include("returned" => 1, "has_more" => viewer != participant)
    end
  end

  it "returns a structured internal error when a tool unexpectedly fails" do
    failure_message = "private implementation failure"
    primitive = DiscourseMcp.registry.find(:tool, "discourse_current_user_get")
    primitive.implementation.stubs(:call).raises(StandardError, failure_message)

    post "/mcp", params: payload.to_json, headers: headers

    expect(response.status).to eq(500)
    expect(response.parsed_body).to eq(
      "jsonrpc" => "2.0",
      "id" => payload[:id],
      "error" => {
        "code" => -32_603,
        "message" => "Internal error",
      },
    )
    expect(response.body).not_to include(failure_message)
  end

  context "when login is required" do
    before { SiteSetting.login_required = true }

    it "lists tools using a bearer token without a browser session" do
      list_payload = payload.merge(method: "tools/list", params: payload[:params].slice(:_meta))
      list_headers = headers.except("HTTP_MCP_NAME").merge("HTTP_MCP_METHOD" => "tools/list")

      post "/mcp", params: list_payload.to_json, headers: list_headers

      expect(response.status).to eq(200)
      expect(response.parsed_body.dig("result", "tools").pluck("name")).to contain_exactly(
        "discourse_current_user_get",
      )
    end

    it "calls tools using a bearer token without a browser session" do
      post "/mcp", params: payload.to_json, headers: headers

      expect(response.status).to eq(200)
      expect(response.parsed_body.dig("result", "structuredContent", "username")).to eq(
        admin.username,
      )
    end

    it "challenges requests without a bearer token even with a browser session" do
      sign_in(admin)

      post "/mcp", params: payload.to_json, headers: headers.except("HTTP_AUTHORIZATION")

      expect(response.status).to eq(401)
      expect(response.headers["WWW-Authenticate"]).to eq(
        %(Bearer resource_metadata="#{DiscourseMcp.protected_resource_metadata_url}"),
      )
    end

    it "challenges anonymous requests without a bearer token" do
      post "/mcp", params: payload.to_json, headers: headers.except("HTTP_AUTHORIZATION")

      expect(response.status).to eq(401)
      expect(response.headers["WWW-Authenticate"]).to eq(
        %(Bearer resource_metadata="#{DiscourseMcp.protected_resource_metadata_url}"),
      )
    end

    it "rejects invalid bearer tokens" do
      post "/mcp",
           params: payload.to_json,
           headers: headers.merge("HTTP_AUTHORIZATION" => "Bearer invalid")

      expect(response.status).to eq(401)
      expect(response.headers["WWW-Authenticate"]).to include('error="invalid_token"')
    end

    it "returns not found when MCP is disabled" do
      access_token
      SiteSetting.mcp_server_enabled = false

      post "/mcp", params: payload.to_json, headers: headers

      expect(response.status).to eq(404)
    end
  end

  it "directs unauthenticated clients to resource metadata for scope selection" do
    post "/mcp", params: payload.to_json, headers: headers.except("HTTP_AUTHORIZATION")

    expect(response.status).to eq(401)
    expect(response.headers["WWW-Authenticate"]).to eq(
      %(Bearer resource_metadata="#{DiscourseMcp.protected_resource_metadata_url}"),
    )
    expect(response.parsed_body.dig("error", "code")).to eq(-32_001)
  end

  it "rejects an invalid bearer credential with an RFC 6750 error" do
    post "/mcp",
         params: payload.to_json,
         headers: headers.merge("HTTP_AUTHORIZATION" => "bearer invalid")

    expect(response.status).to eq(401)
    expect(response.headers["WWW-Authenticate"]).to include('error="invalid_token"')
  end

  it "returns an OAuth insufficient-scope challenge for an exposed tool" do
    SiteSetting.login_required = true
    McpPrimitive.create!(kind: "tool", identifier: "discourse_read_post", enabled: true)
    scoped_payload =
      payload.deep_merge(
        method: "tools/call",
        params: {
          name: "discourse_read_post",
          arguments: {
            post_id: 1,
          },
        },
      )
    scoped_headers = headers.merge("HTTP_MCP_NAME" => "discourse_read_post")

    post "/mcp", params: scoped_payload.to_json, headers: scoped_headers

    expect(response.status).to eq(403)
    expect(response.headers["WWW-Authenticate"]).to include(
      'error="insufficient_scope"',
      'scope="mcp:content:read"',
    )
  end

  it "does not allow content-write access to update a profile" do
    McpPrimitive.create!(kind: "tool", identifier: "discourse_update_user", enabled: true)
    scoped_payload =
      payload.deep_merge(
        params: {
          name: "discourse_update_user",
          arguments: {
            username: admin.username,
            bio_raw: "Changed without profile access",
          },
        },
      )
    scoped_headers = headers.merge("HTTP_MCP_NAME" => "discourse_update_user")
    content_write_authorization =
      DiscourseMcp::OAuth::AuthorizationGrant.create!(
        user: admin,
        client:,
        redirect_uri: client.redirect_uris.first,
        requested_scopes: %w[mcp:profile:read mcp:content:write],
      )
    content_write_token = McpOauthAccessToken.issue!(authorization: content_write_authorization)
    scoped_headers["HTTP_AUTHORIZATION"] = "Bearer #{content_write_token}"

    post "/mcp", params: scoped_payload.to_json, headers: scoped_headers

    expect(response.status).to eq(403)
    expect(response.headers["WWW-Authenticate"]).to include(
      'error="insufficient_scope"',
      'scope="mcp:profile:write"',
    )
    expect(admin.user_profile.reload.bio_raw).not_to eq("Changed without profile access")
  end

  it "omits submitted values from prompt validation errors" do
    McpPrimitive.create!(kind: "prompt", identifier: "discourse.draft_reply", enabled: true)
    prompt_headers = classic_headers
    prompt_authorization =
      DiscourseMcp::OAuth::AuthorizationGrant.create!(
        user: admin,
        client:,
        redirect_uri: client.redirect_uris.first,
        requested_scopes: [DiscourseMcp::INITIAL_SCOPE, DiscourseMcp::Scopes::CONTENT_READ],
      )
    prompt_token = McpOauthAccessToken.issue!(authorization: prompt_authorization)
    instructions = "Confidential draft instructions"

    post "/mcp",
         params: {
           jsonrpc: "2.0",
           id: 1,
           method: "prompts/get",
           params: {
             name: "discourse.draft_reply",
             arguments: {
               instructions:,
             },
           },
         }.to_json,
         headers: prompt_headers.merge("HTTP_AUTHORIZATION" => "Bearer #{prompt_token}")

    expect(response.status).to eq(400)
    expect(response.parsed_body.dig("error", "code")).to eq(-32_602)
    expect(response.parsed_body.dig("error", "data", "errors")).to contain_exactly(
      "type" => "required",
      "data_pointer" => "",
      "schema_pointer" => "",
    )
    expect(response.body).not_to include(instructions)
  end

  it "negotiates a compatible protocol through the standard initialize request" do
    post "/mcp",
         params: initialize_payload.to_json,
         headers: classic_headers.except("HTTP_MCP_PROTOCOL_VERSION")

    expect(response.status).to eq(200)
    expect(response.parsed_body.dig("result", "protocolVersion")).to eq(
      DiscourseMcp::LEGACY_PROTOCOL_VERSION,
    )
    expect(response.parsed_body.dig("result", "serverInfo", "name")).to eq("discourse")
    expect(response.parsed_body.dig("result", "capabilities", "tools")).to eq(
      "listChanged" => false,
    )
  end

  it "keeps legacy initialization on the classic protocol for an unsupported version" do
    unsupported_initialize_payload =
      initialize_payload.deep_merge(params: { protocolVersion: "2025-06-18" })

    post "/mcp",
         params: unsupported_initialize_payload.to_json,
         headers: classic_headers.except("HTTP_MCP_PROTOCOL_VERSION")

    expect(response.status).to eq(200)
    expect(response.parsed_body.dig("result", "protocolVersion")).to eq(
      DiscourseMcp::LEGACY_PROTOCOL_VERSION,
    )
  end

  it "accepts compatible stateless requests without dated request metadata" do
    notification = { jsonrpc: "2.0", method: "notifications/initialized" }
    post "/mcp", params: notification.to_json, headers: classic_headers
    expect(response.status).to eq(202)
    expect(response.body).to be_blank

    list_request = { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }
    post "/mcp", params: list_request.to_json, headers: classic_headers

    expect(response.status).to eq(200)
    expect(response.parsed_body.dig("result", "tools")).to be_an(Array)
  end

  it "lists tools with underscore-only names" do
    list_request = { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }

    post "/mcp", params: list_request.to_json, headers: classic_headers

    tools = response.parsed_body.dig("result", "tools")
    tool_names = tools.pluck("name")
    expect(tool_names).to include("discourse_current_user_get")
    expect(tool_names).to all(match(/\A[A-Za-z0-9_]+\z/))
    expect(tools).to all(include("outputSchema" => include("type" => "object")))
  end

  it "uses the server-wide cache TTL setting for cacheable responses" do
    SiteSetting.mcp_cache_ttl_ms = 12_345
    discover_payload =
      payload.deep_merge(
        method: "server/discover",
        params: {
          _meta: {
            "io.modelcontextprotocol/protocolVersion" => DiscourseMcp::PROTOCOL_VERSION,
            "io.modelcontextprotocol/clientCapabilities" => {
            },
          },
        },
      )
    discover_headers = headers.except("HTTP_MCP_NAME").merge("HTTP_MCP_METHOD" => "server/discover")

    post "/mcp", params: discover_payload.to_json, headers: discover_headers

    expect(response.status).to eq(200)
    expect(response.parsed_body.dig("result", "ttlMs")).to eq(12_345)
  end

  it "executes a stateless dated-protocol tool request" do
    post "/mcp", params: payload.to_json, headers: headers

    expect(response.status).to eq(200)
    expect(response.parsed_body.dig("result", "structuredContent", "username")).to eq(
      admin.username,
    )
    expect(response.parsed_body.dig("result", "resultType")).to eq("complete")
  end

  it "records tool calls with long JSON-RPC request IDs" do
    request_id = "a" * 256

    expect do
      post "/mcp", params: payload.merge(id: request_id).to_json, headers: headers
    end.to change(McpAuditLog, :count).by(1)

    expect(response.status).to eq(200)
    expect(McpAuditLog.last.request_id).to eq(request_id)
  end

  it "records at most one rate-limit audit event per client each minute" do
    SiteSetting.mcp_global_rate_limit_per_minute = 10
    RateLimiter.enable

    12.times { post "/mcp", params: payload.to_json, headers: headers }

    expect(response.status).to eq(429)
    expect(McpAuditLog.where(outcome: "rate_limited").count).to eq(1)
  end
end