Skip to main content

Public search of a knowledge base (MCP)

The search_knowledge_public MCP tool searches a knowledge base as a visitor sees it on a distribution channel: only content published on that channel is returned, and each question comes with its complete published answer. It can be called from any MCP client (an agent, an assistant, a script) through the Smart Tribune MCP gateway.

info

This is the public view, not an inventory. Drafts, answers written for other channels, questions and guides without an active thematic, and documents that cannot be viewed are never returned: their absence says nothing about whether they exist.

Prerequisites​

  • Smart Tribune API credentials (a key and a secret), the same as for the Smart Tribune API. Ask your Smart Tribune contact if you do not have any.
  • A client that speaks MCP over HTTP (the streamable HTTP transport).

Authenticating​

The tool uses the same token as the Smart Tribune API. It has no identity of its own: it acts with the token you present, and never sees more than your credentials allow.

  1. Get a token by sending your credentials to POST https://api-gateway.app.smart-tribune.com/v1/auth. The request body and the response are described in the API reference, Authentication section. The token is the token field of the response.
  2. Send it with every MCP request in the Authorization: Bearer <token> header.

To find the bases your credentials can reach, and so the knowledge_base_id values to use, call GET /v1/knowledge-bases with the same token.

Your token is your responsibility​

Getting this token, protecting it and renewing it is up to you.

  • The token is valid for 1 hour. Renew it before it expires: an expired token is rejected, and the call fails.
  • Reuse it until it expires rather than requesting one for every call: /v1/auth is limited to 2 requests per second.
  • An MCP session does not renew the token. When you change tokens, open a new session (see below).
  • The token gives access to every base of your credentials: do not pass it on, do not log it, do not store it in clear text. The same goes for your credentials, which must never end up in code that runs on a visitor's side (browser, mobile app).

Endpoint​

ItemValue
URLhttps://api-gateway.app.smart-tribune.com/mcp
MethodPOST, JSON-RPC 2.0 body
Tool namest-search__search_knowledge_public

Every request carries three headers:

Content-Type: application/json
Accept: application/json, text/event-stream
Authorization: Bearer <token>

The Accept header must list both types: the gateway may answer in JSON or as an SSE stream, in which each message is a data: {...} line.

A session is required​

The gateway requires an MCP session. A tool call sent without a session is rejected with missing session ID. The exchange takes three steps:

  1. initialize: the gateway opens the session and returns its identifier in the Mcp-Session-Id response header.
  2. notifications/initialized: you confirm the opening, with the Mcp-Session-Id header.
  3. tools/call (and tools/list): every call carries the same Mcp-Session-Id header.

A session serves several calls. Open a new one when you renew your token.

Rate limit​

The gateway accepts 10 requests per second per IP address. The limit applies to all the traffic coming from one address: a server that calls the tool for many users shares these 10 requests between them. Every MCP request counts: initialize, notifications/initialized, tools/list, tools/call, and the DELETE that closes a session.

Above the limit, the gateway answers HTTP 429 with an empty body, and the request does not reach the tool. The response carries three headers:

HeaderMeaning
X-Ratelimit-LimitThe limit and its window, for instance 10, 10;w=1: 10 requests per window of 1 second
X-Ratelimit-RemainingThe requests left in the current window
X-Ratelimit-ResetThe number of seconds before the window starts again

Wait X-Ratelimit-Reset seconds, then send the same request again. A 429 does not close the session: keep the same Mcp-Session-Id. To spend less of the limit, keep one session per token instead of opening one for every call.

Complete example​

GW=https://api-gateway.app.smart-tribune.com/mcp
# $ST_JWT: the token obtained from /v1/auth (see "Authenticating")
H=(-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -H "authorization: Bearer $ST_JWT")

# 1. Open the session and get its identifier
SID=$(curl -sS -D - -o /dev/null "$GW" "${H[@]}" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"my-client","version":"1.0"}}}' \
| tr -d '\r' | sed -n 's/^[Mm]cp-[Ss]ession-[Ii]d: //p')

# 2. Confirm the opening
curl -sS "$GW" "${H[@]}" -H "mcp-session-id: $SID" \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'

# 3. Call the tool
curl -sS "$GW" "${H[@]}" -H "mcp-session-id: $SID" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{
"name":"st-search__search_knowledge_public",
"arguments":{"knowledge_base_id":42,"locale":"en","query":"cancel my contract"}}}' \
| sed -n 's/^data: //p; /^{/p'

Arguments​

ArgumentTypeDefaultDescription
knowledge_base_idinteger ≥ 1requiredThe base to search.
localelanguage coderequiredA language of the base, for instance fr or en_GB.
querytext, 255 characters max.—The words to search for. Without query, the tool lists the published content.
channelfaq, push, bot, contact, contextfaqThe channel whose public view is searched.
knowledge_typelist of question, guide, document["question"]The content types to search.
slugtext—Exact lookup by slug: returns that content or nothing. Cannot be combined with query.
thematicslist of names (50 max.)—Filters on thematics, by their system name (the name of a result's thematics, never their title).
thematics_matchany, allanyany: at least one of the thematics; all: all of them.
tagslist of names (50 max.)—Filters on tags, by their system name (the name of a result's tags, never their title).
tags_matchany, allanyany: at least one of the tags; all: all of them.
exact_matchbooleanfalseSearches the words exactly, without spelling correction.
promotedboolean—true: promoted content only.
frequentboolean—true: content marked as frequent only.
metadata_date_filterslist (20 max.)—Date ranges on document metadata: {"name", "start_date", "end_date"}, all of them required at once.
metadata_sort{"name", "order"}—Sorts the list by a metadata field (order: asc or desc). Without query only.
limit1 to 205Results per page.
pageinteger ≥ 11Page number. page × limit cannot exceed 200.
Whole days only

The bounds of metadata_date_filters are written YYYY-MM-DD. A time (YYYY-MM-DD HH:MM:SS) is accepted but ignored: the filter covers whole days, from 00:00:00 to 23:59:59. A request for "10 am to 12 pm" therefore returns the whole day.

Several thematics and several tags cannot both be any in the same call: the engine would return content with one of the thematics or one of the tags. Set one of the two lists to all, or run two searches.

An unknown or mistyped argument is rejected with a JSON-RPC error: nothing is silently ignored.

Response​

On success, result.isError is false and result.structuredContent contains:

FieldDescription
knowledge_base_id, locale, channelWhat was searched.
queryThe words given (absent for a list).
exact_matchThe search mode used.
spelling_correctionPresent whenever there is a query (see below).
totalThe number of results of the whole search, not of the page.
total_is_lower_boundtrue when there are at least total results.
page, limit, has_morePagination.
resultsThe results of the page.

Each result carries type, id, title, slug, thematics, tags, updated_at, and score for a search.

thematics (the active thematics) and tags are lists of {"name", "title"} objects: the name is the system name to pass to the filters, the title is the label to show. The two almost always differ, for instance {"name": "categorie-3-138", "title": "catégorie 3"}.

Depending on its type:

  • question: answer, its complete published answer on the searched channel, in Markdown;
  • guide: first_step_id and steps, the complete decision tree (id, title, body in Markdown, choices with label and target_step_id or link);
  • document: the file's url and metadatas.

To find out how many items match, ask for limit: 1 and read total.

Spelling correction​

Without exact_match, the engine may correct the words. When spelling_correction.applied is true, the results match spelling_correction.executed_query and not the words typed: tell the user, for instance "results for contract (instead of contrat)".

When a search returns total: 0 without exact_match, the correction has already been tried: nothing matches, neither as typed nor corrected.

Refusals and errors​

A refusal is not an empty result. It comes as an HTTP 200 response with result.isError: true and a message in result.content[0].text:

SituationWhat you receive
No token at the gatewayHTTP 401
Too many requestsHTTP 429, empty body: wait X-Ratelimit-Reset seconds (see Rate limit)
Call without a sessionmissing session ID
Tool name unknown to the gatewayunknown backend …: check the st-search__ prefix
Expired or unreadable tokenThe caller's token could not be verified.: get a new token from /v1/auth, open a new session
Missing rightA message saying that a right is missing
Base outside the account's perimeter, or unknownA message saying so — this is not an absence of content
Language missing from the baseA message listing the base's languages
Invalid argument (dates, limits, combinations)A message naming the argument and the rule
Search failureA message saying the search failed — this is not an empty result

An empty result (results: [], total: 0), on the other hand, is a real answer: nothing published on that channel matches.

Using the tool in an agent​

An agent does not call the tool itself: it presents it to the model, which decides when to search and with which arguments. The agent's code keeps three responsibilities, which must never be handed to the model.

1. The token stays in the agent's code​

The token is an HTTP header of the MCP connection, not an argument of the tool. The model never sees it and must never receive it. The agent gets it from /v1/auth (see Authenticating) and renews it before the hour is up.

A token that is missing or rejected by the gateway makes the connection itself fail: with the Python SDK, initialize raises an MCPError. It is not a refusal the model could read.

The gateway requires a session, and a session does not change tokens. The agent therefore keeps one session per token. When it renews the token, or when a call is refused with The caller's token could not be verified., it requests a new token and opens a new session.

When the agent serves a base, a language and a channel known in advance, its code sets knowledge_base_id, locale and channel, not the model. The model only chooses what depends on the question: query, the filters, the pagination. A model then can neither search another base of your credentials nor pick the wrong language.

3. The agent passes the tool description on unchanged​

The tool description (tools/list) tells the model how to read results and refusals:

  • a refusal is not an empty result;
  • the thematics and tags filters take the name, never the title;
  • an applied spelling correction must be reported to the user.

Do not shorten it and do not rewrite it. If the agent sets arguments itself (point 2), only remove them from the schema shown to the model.

Give the model the result's content, refusals included: that is where it reads why a call failed and how to recover. The structuredContent is meant for the agent's code.

Example with the Python MCP SDK​

This example uses version 2 of the Python MCP SDK. The SDK runs the initialize itself and carries the Mcp-Session-Id header. It runs as is: replace SCOPE with your base, language and channel, then:

pip install "mcp>=2,<3"
export ST_JWT=... # the token obtained from /v1/auth, without "Bearer"
python agent.py
agent.py
import asyncio
import os

import httpx2
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

GATEWAY = "https://api-gateway.app.smart-tribune.com/mcp"
TOOL = "st-search__search_knowledge_public"

# Set by the agent, never by the model (point 2).
SCOPE = {"knowledge_base_id": 42, "locale": "en", "channel": "faq"}


async def run(token: str) -> None:
"""One session per token: call it again with the next token."""
http_client = httpx2.AsyncClient(
headers={"Authorization": f"Bearer {token}"},
timeout=httpx2.Timeout(30, read=300),
)
async with http_client:
async with streamable_http_client(GATEWAY, http_client=http_client) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()

tools = await session.list_tools()
tool = next((t for t in tools.tools if t.name == TOOL), None)
if tool is None:
raise SystemExit(f"{TOOL} is not exposed: check the gateway URL.")
# Show the model tool.description unchanged, and tool.input_schema
# without the properties of SCOPE.
left_to_the_model = sorted(
name for name in tool.input_schema["properties"] if name not in SCOPE
)
print(f"Tool found. Arguments left to the model: {left_to_the_model}")

# When the model asks for a search with model_arguments.
# SCOPE comes last: it wins over what the model sends.
model_arguments = {"query": "cancel my contract", "limit": 3}
result = await session.call_tool(TOOL, {**model_arguments, **SCOPE})

# For the model, refusals included (point 3).
for_the_model = "\n".join(
block.text for block in result.content if block.type == "text"
)
# For the agent's code, only when the call succeeded.
if result.is_error:
print(f"Refused: {for_the_model}")
else:
found = result.structured_content
kb_id, total = found["knowledge_base_id"], found["total"]
print(f"Search: {total} result(s) in base {kb_id}")
for item in found["results"]:
print(f"- [{item['id']}] {item['title']}")

# A refusal comes back as a result, not as an exception.
refused = await session.call_tool(TOOL, {**SCOPE, "knowledge_base_id": 999999})
print(f"Expected refusal (is_error={refused.is_error}): {refused.content[0].text}")


if __name__ == "__main__":
asyncio.run(run(os.environ["ST_JWT"]))

What you should see (the results depend on your base):

Tool found. Arguments left to the model: ['exact_match', 'frequent', 'knowledge_type', 'limit', 'metadata_date_filters', 'metadata_sort', 'page', 'promoted', 'query', 'slug', 'tags', 'tags_match', 'thematics', 'thematics_match']
Search: 4 result(s) in base 42
- [1187] How do I cancel my contract?
- [1203] What is the notice period for cancelling?
- [1311] Can I cancel online?
Expected refusal (is_error=True): Knowledge base 999999 is unknown to this service, so nothing was searched. Report that the base could not be resolved — this is NOT an empty result.
  • An MCPError raised by initialize: the gateway rejected the token. It is expired, missing or badly copied: get a new one from /v1/auth.
  • Refused: … instead of Search: …: the message says why, for instance a base outside the perimeter of your credentials or a language the base does not have.
  • st-search__search_knowledge_public is not exposed: the gateway does not offer the tool at that URL. Check the URL and the tool name.