Build a knowledge-base MCP for internal docs (2026 tutorial)
Tutorial · Advanced

Build a knowledge-base MCP for internal docs

Turn your team's wiki, ADRs, or internal docs into an MCP server that Claude Code can query. When someone asks about a domain, Claude reaches for your docs before its training data.

55 minAdvancedUpdated Aug 2026

Prerequisites

  • Familiar with building an MCP server from scratch
  • Access to your team's docs (Confluence, Notion, GitHub wikis, or plain markdown)
  • Node.js 20+ or Python 3.11+ available
  • Understanding of semantic search fundamentals (embeddings, vector similarity)

What you'll learn

  • How to index heterogeneous doc sources into a single searchable store
  • How to expose search + retrieval as MCP tools
  • How to handle access control (not every doc is for every user)
  • How to keep the index fresh without hammering source systems
  • The specific patterns that make internal doc MCPs useful vs frustrating

Every team has docs Claude doesn't know about — internal ADRs, runbooks, wiki pages, team norms. When Claude answers questions in these domains, it either says "I don't know" or (worse) confidently makes something up based on generic knowledge. A knowledge-base MCP fixes this: Claude reaches for your docs when relevant, produces answers grounded in what your team actually wrote.

This tutorial builds the MCP end-to-end — indexing, search, retrieval, access control. The example uses a mix of markdown files in a git repo and Notion pages, but the pattern generalizes to any doc source with an API.

1
Decide what to index

The first design decision — what docs go in the MCP and what stays out. Not all docs are equal:

Good candidates:

  • ADRs (architectural decisions and their context)
  • Runbooks (specific operational procedures)
  • API docs for internal services
  • Team standards and conventions
  • Historical context ("why we do X this way")

Bad candidates:

  • Meeting notes (usually stale and unstructured)
  • Draft docs and WIPs (misleading if used as authoritative)
  • Docs from other teams you shouldn't reference
  • Content that's already in the codebase (comments, READMEs)
  • Anything sensitive (customer data, financials)
The scope test

If Claude cited this doc in a response, would that be useful and accurate? For your team's ADR on why you use Postgres: yes. For a two-year-old draft that was superseded: no. Curate the source list before indexing.

2
Design the indexing pipeline

The pipeline shape:

Indexing pipeline
Source docs (markdown, Notion, Confluence)
    ↓
Fetch & extract text
    ↓
Chunk into passages (500-1000 tokens each)
    ↓
Generate embeddings (via OpenAI, Voyage, or similar)
    ↓
Store in vector DB (Pinecone, Weaviate, pg_vector)
    +
Store metadata (source URL, last modified, access level)
    ↓
Ready for query via MCP

The two stores serve different purposes: the vector DB does similarity search; the metadata store enforces access control and provides source attribution. Both are essential.

src/indexer/index.ts
import { fetchGitDocs } from './sources/git.js';
import { fetchNotionPages } from './sources/notion.js';
import { chunkDoc } from './chunker.js';
import { embed } from './embed.js';
import { upsertToVectorDB, upsertMetadata } from './stores.js';

export async function reindex() {
  const sources = [
    ...await fetchGitDocs({ repo: 'internal-docs', paths: ['adrs/', 'runbooks/'] }),
    ...await fetchNotionPages({ workspaceId: '...', dbId: 'engineering-docs' }),
  ];

  for (const doc of sources) {
    // Skip docs that shouldn't be indexed
    if (shouldSkip(doc)) continue;

    // Chunk
    const chunks = chunkDoc(doc);

    // Embed each chunk
    for (const chunk of chunks) {
      const embedding = await embed(chunk.text);
      await upsertToVectorDB({
        id: `${doc.id}-${chunk.index}`,
        vector: embedding,
        metadata: {
          docId: doc.id,
          chunkIndex: chunk.index,
        },
      });
      await upsertMetadata({
        docId: doc.id,
        title: doc.title,
        source: doc.sourceUrl,
        lastModified: doc.lastModified,
        accessLevel: doc.accessLevel,
      });
    }
  }
}
3
Handle access control from the start

Different docs have different access levels. Some are public within the company; some are team-specific; some are role-restricted. The MCP needs to respect these.

Two enforcement points:

1. At index time: capture the access level of each doc.

2. At query time: filter results by the caller's access level.

Access control at query
export async function searchDocs(query: string, callerContext: CallerContext) {
  // Embed the query
  const queryVector = await embed(query);

  // Search vector DB
  const results = await vectorDB.search(queryVector, { limit: 20 });

  // Filter by access control
  const filtered = [];
  for (const result of results) {
    const meta = await getMetadata(result.docId);
    if (canAccess(callerContext, meta.accessLevel)) {
      filtered.push({ result, meta });
    }
  }

  // Return top 5 accessible results
  return filtered.slice(0, 5);
}

function canAccess(caller: CallerContext, level: AccessLevel) {
  if (level === 'public') return true;
  if (level === 'engineering' && caller.team === 'engineering') return true;
  if (level === 'team-x' && caller.subteams.includes('team-x')) return true;
  return false;
}
Don't skip this

An MCP that returns any doc to any caller is a data leak waiting to happen. Someone in Sales asks Claude a technical question; the MCP returns a confidential architecture doc. Access control isn't optional; it's the security boundary.

4
Expose the MCP tools

The tool surface should be small — usually 2-3 tools, not 10.

src/tools/search-docs.ts
export const searchDocsTool = {
  name: 'search_docs',
  description: `Search internal documentation. Use this BEFORE answering 
questions about our team's systems, standards, or historical decisions.
Do NOT use for generic technical questions (use your training knowledge).

Good uses: "how does our checkout service handle retries", 
"what's our team's convention for error handling", 
"why did we choose Postgres over MongoDB"`,
  inputSchema: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: 'Natural language query about internal topic',
      },
    },
    required: ['query'],
  },
};

export async function searchDocsHandler(args: unknown, context: CallerContext) {
  const parsed = SearchArgsSchema.parse(args);
  const results = await searchDocs(parsed.query, context);

  if (results.length === 0) {
    return {
      content: [{
        type: 'text',
        text: 'No internal docs found for this query. Fall back to your training knowledge or ask the user for more context.',
      }],
    };
  }

  return {
    content: [{
      type: 'text',
      text: JSON.stringify({
        results: results.map(r => ({
          title: r.meta.title,
          source: r.meta.source,
          lastModified: r.meta.lastModified,
          excerpt: r.result.text,
        })),
      }, null, 2),
    }],
  };
}

Notice the tool description — it tells Claude when to use it AND when NOT to. This is the single most important field for correct tool selection. Vague descriptions cause Claude to reach for the tool too often or too rarely.

5
Keep the index fresh

A stale index is worse than no index — Claude confidently cites out-of-date info. Reindexing strategies:

Full reindex nightly: simple, wasteful. Fine for small doc collections.

Incremental via webhooks: source systems (Notion, Confluence) can webhook on updates. Best fidelity but more complex.

Poll changed-since: query each source for docs modified since last index. Middle ground.

For most teams, nightly full reindex is fine to start. When your doc collection grows or updates are frequent, move to incremental.

.github/workflows/reindex-docs.yml
name: Reindex knowledge-base MCP
on:
  schedule:
    - cron: '0 3 * * *'  # 3am UTC daily
  workflow_dispatch:

jobs:
  reindex:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: pnpm install
      - run: pnpm reindex
        env:
          NOTION_TOKEN: ${{ secrets.NOTION_TOKEN }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          VECTOR_DB_URL: ${{ secrets.VECTOR_DB_URL }}
      - name: Notify on failure
        if: failure()
        run: |
          # Post to Slack
          curl -X POST ${{ secrets.SLACK_WEBHOOK }} \
            -d '{"text": "Docs reindex failed"}'
6
Register the MCP with your team

Update the team's cctk config to include the new MCP:

.claude/mcp.json (committed to repo)
{
  "servers": {
    "internal-docs": {
      "command": "node",
      "args": ["dist/mcp-server.js"],
      "env": {
        "MCP_ENDPOINT": "https://docs-mcp.internal.example.com",
        "MCP_AUTH_TOKEN": "${TEAM_DOCS_MCP_TOKEN}"
      }
    }
  }
}

Announce to the team what the MCP covers and how it activates. Something like:

"We now have a knowledge-base MCP indexed over our ADRs, runbooks, and engineering wiki. Claude will use it automatically when answering questions about our systems. If you notice cases where it should have activated but didn't, or where it activated incorrectly, let me know — I'll tune the tool description."

🧪 Try it now

Test on 5-10 real queries about your team's systems. Does Claude reach for the MCP? Are the results useful? Are there queries where it should have used the MCP but didn't? Tune the tool description based on what you find.

Recap

You built a knowledge-base MCP for your team's internal docs — indexing pipeline, vector search, access control, and integration with Claude Code. Now Claude reaches for your team's actual docs when relevant.

The design decisions that matter: curated source list (not everything), access control from day one, narrow tool surface with precise descriptions, fresh index via automation, respect for what should stay in humans-only channels.

This pattern extends: same shape for a customer-support knowledge base, a compliance-docs MCP, a design-system reference MCP. What varies is the source list and access model; what stays the same is the architecture.

Common gotchas

  • Claude ignores the MCP even when it would help: Tool description is too vague. Include specific example queries where the MCP should be used. "Use this when the user asks about X, Y, Z" is stronger than "use for internal questions."
  • Claude cites the MCP for questions it shouldn't: Add explicit "do NOT use for" cases. "Do not use for generic questions about JavaScript" prevents the MCP from being invoked on questions your training data handles better.
  • Access control feels annoying to maintain: Simplify. Most teams need at most 3-4 access levels (public / engineering / specific-team / restricted). Complex ACL systems create maintenance burden without proportional benefit. Start simple; add complexity only when you have a specific need.
  • Reindexing takes forever: Move from full to incremental. Track last-modified per source; only reindex what changed. For very large collections, this is essential — full reindex just doesn't scale.
  • Claude cites outdated docs: Two fixes: (1) reindex more frequently, (2) include lastModified in results so Claude can note "as of [date]." Users can then ask about the freshness. This is a communication fix as much as a technical one.

Get cctk to skip the boilerplate

Everything in this tutorial is already scaffolded in cctk — commands, subagents, hooks, MCP configs. Install and customize instead of starting from scratch.

npx cctk@latest init Get cctk v1.5.2 →