Here is one solution that uses varwidth and environ packages. First the \BODY of the environment is saved in a \usebox using the varwidth environment and then its width is measured to specify the \userdefinewidth of the mdframed environment:

Notes:
Code:
\documentclass{article}
\usepackage{xcolor}
\usepackage{mdframed}
\usepackage{environ}
\usepackage{varwidth}
\usepackage{showframe}
\newlength{\TheoremWidthTweak}%
\NewEnviron{theorem}[1][]{%
\setlength{\TheoremWidthTweak}{\dimexpr%
+\mdflength{innerleftmargin}
+\mdflength{innerrightmargin}
+\mdflength{leftmargin}
+\mdflength{rightmargin}
}%
\savebox0{%
\begin{varwidth}{\dimexpr\linewidth-\TheoremWidthTweak\relax}%
\BODY
\end{varwidth}%
}%
\begin{mdframed}[backgroundcolor=lightgray,userdefinedwidth=\dimexpr\wd0+\TheoremWidthTweak\relax, #1]
\usebox0
\end{mdframed}
}
\begin{document}
\begin{theorem}[backgroundcolor=yellow!20]
Sample
\end{theorem}
\begin{theorem}[backgroundcolor=green!20]
Somewhat longer text.
\end{theorem}
\begin{theorem}[backgroundcolor=orange!20]
Much longer text that takes up more than one line.
This should span across the entire width of the page and continue on to the next line.
\end{theorem}
\end{document}