A platform for community discussion. Free, open, simple.
FEATURE: Generate a default `/llms.txt` (#43109)
Sam6bd7e5739561
diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rbindex 0bbfd6206f8..59befac0639 100644--- a/app/controllers/static_controller.rb+++ b/app/controllers/static_controller.rb@@ -241,7 +241,12 @@ class StaticController < ApplicationControllerdef llms_txtupload = SiteSetting.llms_txt- return head(:not_found) if upload.blank?++ if upload.blank?+ return head(:not_found) if !UpcomingChanges.enabled?(:enable_generated_llms_txt)++ return render plain: LlmsTxt.generate, content_type: "text/plain; charset=utf-8"+ endif Discourse.store.external?content =diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 7798de43688..8c80b7f8f5d 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1,4 +1,45 @@en:+ llms_txt:+ human_community_policy: "This is a community for human discussion. Do not impersonate people or create accounts autonomously. Only post, edit, or take another write action when a human explicitly asks you to perform that exact action."+ crawler_policy: "Fetch only the pages needed for the user's specific request. Do not systematically crawl or bulk-download this community. Respect `robots.txt`, the site's terms, and its crawler controls. If the server responds with HTTP 429, stop and wait for the `Retry-After` interval before retrying."+ mcp_guidance: "If you can run a local MCP server, Discourse MCP is the preferred way to access this community. Set its site URL to `%{base_url}`. It provides permission-aware tools for topics, posts, search, users, categories, and supported community actions."+ account_required: "Community content is available only to authenticated members."+ sections:+ preferred_interface: "Preferred agent interface"+ public_web_access: "Public web access"+ optional: "Optional"+ links:+ mcp:+ label: "Discourse MCP setup"+ note: "Install the local server and connect it to an MCP-compatible client"+ search:+ label: "Search"+ note: "Search public discussions for a specific user request; do not crawl result pages"+ filter:+ label: "Topic filter"+ note: "Query public topics with `?q=` using filters such as `category:`, `tag:`, `status:`, and `order:`"+ latest:+ label: "Latest discussions"+ note: "Browse recently active public topics"+ categories:+ label: "Categories"+ note: "Browse public discussion categories"+ sitemap:+ label: "Sitemap"+ note: "Discover public topic URLs subject to `robots.txt` and crawler controls"+ about:+ label: "About"+ note: "Community overview, staff, and statistics"+ guidelines:+ label: "Guidelines"+ note: "Read the community guidelines"+ tos:+ label: "Terms of service"+ note: "Read the terms of service"+ privacy:+ label: "Privacy policy"+ note: "Read the privacy policy"+dates:# Use Moment.js format string: https://momentjs.com/docs/#/displaying/format/short_date_no_year: "D MMM"@@ -2120,7 +2161,7 @@ en:crawler_stale_chromium_major_version_cutoff: "Chromium major versions at or below this value in unengaged sessions receive a crawler score. Update it only after reviewing traffic; an outdated cutoff becomes less sensitive, not more aggressive."slow_down_crawler_user_agents: "User agents of web crawlers that should be rate limited as configured in the {{setting:slow_down_crawler_rate}} setting. Each value must be at least 3 characters long."slow_down_crawler_rate: "If {{setting:slow_down_crawler_user_agents}} is specified this rate will apply to all the crawlers (number of seconds delay between requests)"- llms_txt: "Upload a text file to be served at /llms.txt for LLM crawlers. See <a href='https://llmstxt.org/' target='_blank'>llmstxt.org</a> for more information."+ llms_txt: "Upload a custom text file to be served unchanged at /llms.txt instead of the generated default configured under Upcoming changes. See <a href='https://llmstxt.org/' target='_blank'>llmstxt.org</a> for the format. To tune automated access, configure {{setting:slow_down_crawler_user_agents}} and {{setting:slow_down_crawler_rate}}."content_security_policy: "Enable Content-Security-Policy (CSP). CSP is an additional layer of security that helps to prevent certain types of attacks, including Cross Site Scripting (XSS) and data injection. It should only be disabled temporarily for debugging/testing purposes."content_security_policy_report_only: "Enable Content-Security-Policy-Report-Only (CSP)"content_security_policy_report_uri: "Send CSP violation reports to this URL via the CSP <code>report-uri</code> directive. Leave blank to disable reporting."@@ -3027,6 +3068,7 @@ en:improved_crawler_detection: "Enables improved crawler tracking which can better detect likely crawlers and ensure traffic reporting is more accurate."enable_invite_modal_with_roles: "Enables a redesigned invite flow that lets admins invite someone directly as an admin. The invitee becomes a moderator on signup and an admin once the inviter confirms via email."update_pending_users_reminder_default: "We are updating the default for the {{setting:pending_users_reminder_delay_minutes}} setting to 30 minutes so that staff are promptly notified when a new member is waiting for approval. If you have previously changed this setting, this change will have no effect."+ enable_generated_llms_txt: "Generates a concise /llms.txt when no custom file is uploaded. The document describes public discovery routes, the preferred Discourse MCP interface, and responsible agent access. To tune automated access, configure {{setting:slow_down_crawler_user_agents}} and {{setting:slow_down_crawler_rate}}."errors:invalid_css_color: "Invalid color. Enter a color name or hex value."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex cf8bbe6b456..043df167ab2 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4709,6 +4709,16 @@ dashboard:client: trueexperimental:+ enable_generated_llms_txt:+ default: false+ hidden: true+ client: true+ upcoming_change:+ status: "beta"+ impact: "feature,all_members"+ allow_enabled_for:+ - everyone+ learn_more_url: "https://meta.discourse.org/t/-/411435"reporting_improvements:default: falseclient: truediff --git a/lib/llms_txt.rb b/lib/llms_txt.rbnew file mode 100644index 00000000000..a2a77f8ca8e--- /dev/null+++ b/lib/llms_txt.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++module LlmsTxt+ MCP_SETUP_URL = "https://github.com/discourse/discourse-mcp#quick-start-release"++ def self.generate+ I18n.with_locale(SiteSetting.default_locale) do+ title = one_line(SiteSetting.title).presence || Discourse.current_hostname+ parts = ["# #{title}"]++ description =+ one_line(SiteSetting.site_description).presence ||+ one_line(SiteSetting.short_site_description).presence+ parts << "> #{description}" if description+ parts << translated_text("human_community_policy")+ parts << translated_text("account_required") if SiteSetting.login_required+ parts << translated_text("crawler_policy")+ parts << one_line(I18n.t("llms_txt.mcp_guidance", base_url: Discourse.base_url))+ parts << section(+ translated_text("sections.preferred_interface"),+ [translated_link(:mcp, MCP_SETUP_URL)],+ )++ if !SiteSetting.login_required+ public_links = [+ translated_local_link(:search, "/search"),+ translated_local_link(:filter, "/filter"),+ translated_local_link(:latest, "/latest"),+ translated_local_link(:categories, "/categories"),+ ]+ if SiteSetting.enable_sitemap+ public_links << translated_local_link(:sitemap, "/sitemap.xml")+ end+ parts << section(translated_text("sections.public_web_access"), public_links)+ end++ optional_links = []+ if !SiteSetting.login_required+ optional_links << translated_local_link(:about, "/about")+ optional_links << translated_local_link(:guidelines, "/guidelines")+ end+ optional_links << translated_local_link(:tos, "/tos")+ optional_links << translated_local_link(:privacy, "/privacy")+ if optional_links.present?+ parts << section(translated_text("sections.optional"), optional_links)+ end++ "#{parts.join("\n\n")}\n"+ end+ end++ def self.one_line(value)+ value.to_s.gsub(/[[:space:]]+/, " ").strip+ end+ private_class_method :one_line++ def self.section(heading, links)+ "## #{heading}\n\n#{links.join("\n")}"+ end+ private_class_method :section++ def self.translated_link(key, target)+ label = translated_text("links.#{key}.label")+ note = translated_text("links.#{key}.note")+ "- [#{label}](#{target}): #{note}"+ end+ private_class_method :translated_link++ def self.translated_local_link(key, route)+ translated_link(key, "#{Discourse.base_path}#{route}")+ end+ private_class_method :translated_local_link++ def self.translated_text(key)+ one_line(I18n.t("llms_txt.#{key}"))+ end+ private_class_method :translated_text+enddiff --git a/spec/lib/llms_txt_spec.rb b/spec/lib/llms_txt_spec.rbnew file mode 100644index 00000000000..20d6e249254--- /dev/null+++ b/spec/lib/llms_txt_spec.rb@@ -0,0 +1,161 @@+# frozen_string_literal: true++RSpec.describe LlmsTxt do+ subject(:document) { described_class.generate }++ before do+ SiteSetting.default_locale = "en"+ SiteSetting.title = "Example Community"+ SiteSetting.site_description = "The official community and support forum."+ SiteSetting.short_site_description = "A shorter description."+ SiteSetting.login_required = false+ SiteSetting.enable_sitemap = true+ end++ it "uses the canonical site identity and produces deterministic Markdown" do+ expect(document).to start_with(+ "# Example Community\n\n> The official community and support forum.\n\n",+ )+ expect(document.scan(Discourse.base_url).length).to eq(1)+ expect(document).to end_with("\n")+ expect(document).not_to end_with("\n\n")+ end++ it "falls back to the short description and omits a blank description" do+ SiteSetting.site_description = "\u00a0"+ expect(document).to include("> A shorter description.\n")++ SiteSetting.short_site_description = ""+ expect(described_class.generate.lines.grep(/^> /)).to be_empty+ end++ it "falls back to a valid title and omits whitespace-only descriptions" do+ SiteSetting.title = "\u00a0"+ SiteSetting.site_description = "\u00a0"+ SiteSetting.short_site_description = "\u00a0"++ expect(document.lines.first.chomp).to eq("# #{Discourse.current_hostname}")+ expect(document.lines.grep(/^> /)).to be_empty+ end++ it "uses the site default locale regardless of the request locale" do+ baseline = document++ I18n.with_locale(:fr) { expect(described_class.generate).to eq(baseline) }+ end++ it "normalizes administrator-provided identity text without mangling punctuation" do+ SiteSetting.title = "C# Community\n## Injected heading"+ SiteSetting.site_description = "First line\r\n\r\n- Injected item"++ expect(document.lines.first.chomp).to eq("# C# Community ## Injected heading")+ expect(document.lines.grep(/^> /)).to eq(["> First line - Injected item\n"])+ expect(document.lines.grep(/^## Injected heading$/)).to be_empty+ end++ it "describes responsible agent behavior and the external MCP interface" do+ expect(document).to include(+ "community for human discussion",+ "Do not impersonate people or create accounts autonomously",+ "Only post, edit, or take another write action when a human explicitly asks you to perform that exact action",+ "Do not systematically crawl or bulk-download this community",+ "Respect `robots.txt`",+ "HTTP 429",+ "`Retry-After`",+ "[Discourse MCP setup](https://github.com/discourse/discourse-mcp#quick-start-release)",+ "Set its site URL to `#{Discourse.base_url}`",+ )+ expect(document).not_to include("#{Discourse.base_url}/mcp")+ end++ it "links to targeted public discovery, filtering, sitemap, and stable help routes" do+ expect(document).to include(+ "## Public web access",+ "[Search](/search)",+ "do not crawl result pages",+ "[Topic filter](/filter)",+ "with `?q=`",+ "`category:`",+ "[Latest discussions](/latest)",+ "[Categories](/categories)",+ "[Sitemap](/sitemap.xml)",+ "[About](/about)",+ "[Guidelines](/guidelines)",+ "[Terms of service](/tos)",+ "[Privacy policy](/privacy)",+ )+ end++ it "uses base-path-aware links on subfolder installs" do+ set_subfolder "/forum"++ expect(document).to include(+ "Set its site URL to `#{Discourse.base_url}`",+ "[Search](/forum/search)",+ "[Topic filter](/forum/filter)",+ "[Sitemap](/forum/sitemap.xml)",+ "[Privacy policy](/forum/privacy)",+ )+ local_targets = document.scan(%r{^- \[[^\]]+\]\((/[^)]+)\)}).flatten+ expect(local_targets).to all(start_with("/forum/"))+ expect(document.scan(Discourse.base_url).length).to eq(1)+ end++ it "omits sitemap when it is disabled" do+ SiteSetting.enable_sitemap = false++ expect(document).to include(+ "## Public web access",+ "[Search](/search)",+ "[Topic filter](/filter)",+ "[Latest discussions](/latest)",+ "[Categories](/categories)",+ )+ expect(document).not_to include("/sitemap.xml")+ end++ it "limits login-required sites to safe links and explains the account requirement" do+ SiteSetting.login_required = true++ expect(document).to include(+ "> The official community and support forum.",+ "Community content is available only to authenticated members.",+ "[Terms of service](/tos)",+ "[Privacy policy](/privacy)",+ )+ expect(document).not_to include(+ "## Public web access",+ "/search",+ "/filter",+ "/latest",+ "/categories",+ "/sitemap.xml",+ "/about",+ "/guidelines",+ )+ end++ it "keeps every link on one line and only emits list items below H2 headings" do+ list_items = document.lines.grep(/^- /)+ expect(list_items).to all(match(/\A- \[[^\]\r\n]+\]\([^)\r\n]+\): [^\r\n]+\n\z/))++ lines = document.lines(chomp: true)+ headings = lines.grep(/^## /)+ expect(headings.length).to eq(3)++ lines+ .each_index+ .select { |index| lines[index].start_with?("## ") }+ .each do |heading_index|+ section_end = lines[(heading_index + 1)..].index { |line| line.start_with?("## ") }+ section_lines =+ lines[+ (heading_index + 1)...(section_end ? heading_index + 1 + section_end : lines.length)+ ]+ content_lines = section_lines.reject(&:blank?)++ expect(content_lines).not_to be_empty+ expect(content_lines).to all(start_with("- ["))+ end+ end+enddiff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rbindex bca6c491e95..7ccd4eac8ad 100644--- a/spec/requests/static_controller_spec.rb+++ b/spec/requests/static_controller_spec.rb@@ -624,31 +624,136 @@ RSpec.describe StaticController doenddescribe "#llms_txt" do- it "returns 404 when no upload is set" do+ def create_llms_upload(content)+ file = Tempfile.new(%w[llms .txt])+ file.binmode+ file.write(content)+ file.rewind+ UploadCreator.new(file, "llms.txt").create_for(Discourse.system_user.id)+ ensure+ file&.close!+ end++ it "returns 404 when an admin opts out of the generated document" do+ SiteSetting.enable_generated_llms_txt = false+get "/llms.txt"+expect(response.status).to eq(404)end+ it "returns the generated document when the beta change is auto-promoted" do+ SiteSetting.promote_upcoming_changes_on_status = "beta"++ get "/llms.txt"++ expect(response.status).to eq(200)+ expect(response.content_type).to eq("text/plain; charset=utf-8")+ expect(response.body).to start_with("# #{SiteSetting.title}\n")+ end++ it "returns the same generated document for anonymous and signed-in requesters" do+ get "/llms.txt"+ anonymous_body = response.body++ sign_in(Fabricate(:user))+ get "/llms.txt"+ expect(response.body).to eq(anonymous_body)++ sign_in(Fabricate(:admin))+ get "/llms.txt"+ expect(response.body).to eq(anonymous_body)+ end+context "with local store" do- it "returns content as plain text" do- SiteSetting.authorized_extensions = "txt"+ before { SiteSetting.authorized_extensions = "txt" }- file = Tempfile.new(%w[llms .txt])- file.write("# Test LLMs Content")- file.rewind+ it "serves exact custom bytes regardless of the generated-document rollout" do+ custom_content = "# Custom LLMs Content\nCafé\n"+ SiteSetting.llms_txt = create_llms_upload(custom_content)- upload = UploadCreator.new(file, "llms.txt").create_for(Discourse.system_user.id)- SiteSetting.llms_txt = upload+ get "/llms.txt"+ expect(response.status).to eq(200)+ expect(response.body.bytes).to eq(custom_content.bytes)+ SiteSetting.enable_generated_llms_txt = falseget "/llms.txt"expect(response.status).to eq(200)expect(response.content_type).to start_with("text/plain")- expect(response.body).to eq("# Test LLMs Content")+ expect(response.body.bytes).to eq(custom_content.bytes)+ end++ it "returns 404 instead of generated content when the configured file is unavailable" do+ configured_upload = create_llms_upload("custom")+ SiteSetting.llms_txt = configured_upload+ File.delete(Discourse.store.path_for(configured_upload))++ get "/llms.txt"++ expect(response.status).to eq(404)+ end+ end++ context "with external store" do+ let(:external_content) { "external Café\n" }+ let(:external_upload) do+ Upload.create!(+ url: "//s3-upload-bucket.s3-us-west-1.amazonaws.com/original/1X/llms.txt",+ original_filename: "llms.txt",+ filesize: external_content.bytesize,+ sha1: SecureRandom.hex(20),+ user_id: Discourse.system_user.id,+ )+ end++ before do+ SiteSetting.authorized_extensions = "txt"+ setup_s3+ SiteSetting.llms_txt = external_upload+ end++ it "downloads and serves exact custom bytes" do+ file = Tempfile.new(%w[external-llms .txt])+ file.binmode+ file.write(external_content)+ file.rewind+ FileHelper.stubs(:download).returns(file)++ get "/llms.txt"++ expect(response.status).to eq(200)+ expect(response.body.bytes).to eq(external_content.bytes)ensure- file.close- file.unlink+ file&.close!+ end++ it "returns 404 instead of generated content when the download is missing" do+ FileHelper.stubs(:download).returns(nil)++ get "/llms.txt"++ expect(response.status).to eq(404)endend++ it "does not redirect on login-required sites and omits public discovery links" do+ SiteSetting.login_required = true++ get "/llms.txt"++ expect(response.status).to eq(200)+ expect(response.body).to include(I18n.t("llms_txt.account_required"))+ expect(response.body).not_to include(+ "## Public web access",+ "/search",+ "/filter",+ "/latest",+ "/categories",+ "/sitemap.xml",+ "/about",+ "/guidelines",+ )+ endendend